I am trying to define an empty df outside a for loop and then fill the rows/columns from inside the loop, something like this:
df<- data.frame()
for (fl in files){
dt <- read.table(fl, header = FALSE, col.names = c("year","month","value"),
colClasses = c("character","character","numeric"))
t <- aggregate(value ~ year, dt, sum)
df$year <- t$year
df$value <- t$value * someFunction()
}
Now, There are a various ways to create an empty df in R.
df <- data.frame()
# or another method
df <- data.frame(Month=character(),
Value=character(),
stringsAsFactors=FALSE)
# or another method
df <- data.frame(matrix(nrow = 0, ncol = 2))
But when I assign values to the data frame, the following error is produced:
df$Month <- month.abb
Error in `$<-.data.frame`(`*tmp*`, File, value = c("Jan", "Feb", "Mar", :
replacement has 12 rows, data has 0
I don't know what I am doing wrong or any misconception that I might have, but I couldn't find my way around this. Can anyone explain it to me ?
P.S: df <- data.frame(matrix(nrow = 100, ncol = 2)) works but I don't know if its a good idea because my df will have different number of rows.