Message-ID: <fcc2e0a0-ce0a-5e79-dcc8-fde40d39b24f@gmail.com>
Date: 2016-06-09T10:36:11Z
From: Duncan Murdoch
Subject: create an empty data frame and then fill in it
In-Reply-To: <8B435C9568170B469AE31E8891E8CC4F3DBB74BA@ESINO.regionemarche.intra>
On 09/06/2016 6:22 AM, Stefano Sofia wrote:
> Dear R list users,
> sorry for this simple question, but I already spent many efforts to solve it.
>
> I create an empty data frame called df_year like
>
> df_year <- data.frame(day=as.Date(character()), hs_MteBove=integer(), hs_MtePrata=integer(), hs_Pintura=integer(), hs_Pizzo=integer(), hs_Sassotetto=integer(), hs_Sibilla=integer(), stringsAsFactors=FALSE)
>
> and then I start to fill in it with
>
> df_year$day <- seq(as.Date("2004-11-01-00-00","%Y-%m-%d"), as.Date("2005-05-01-00-00","%Y-%m-%d"), by="day")
>
> but I get the following error:
> "replacement has 182 rows, data has 0"
>
> Where is my silly mistake?
Your dataframe has 0 rows, so you can't put a 182 row vector into the
first column.
Unlike vectors, dataframes won't grow if you make assignments beyond the
end of the rows.
There are at least a couple of solutions:
1. Don't create columns until you have data ready for them.
You can wait to create the dataframe until your "day" column is ready:
df_year <- data.frame(day = seq(...))
As you compute other columns of the same length, you can add them, e.g.
df_year$hs_MteBove <- ...
2. Create your columns with the right length from the beginning:
df_year <- data.frame(day = rep(as.Date(NA), 182), ...)
I don't like this solution as much.
Duncan Murdoch