Unfortunately I got stuck and need your help.
I am initializing a data frame and try to fill it with new rows in a loop. It almost works as it should, only the first row gets an "NA" for the row.names value. Can anyone propose a solution for this and/or explain why this happens?
I am using the f3 approach from the answer in this question: How to append rows to an R data frame
Example:
df <- data.frame( "Type" = character(),
"AvgError" = numeric(),
"StandardDeviation"= numeric (),
stringsAsFactors=FALSE)
for (i in 1:3){
df[nrow(df) + 1, ]$Type <- paste("Test", as.character(format(round(i, 2), nsmall = 2)))
df[nrow(df), ]$AvgError <- i/10
df[nrow(df), ]$StandardDeviation <- i/100
}
df
Type AvgError StandardDeviation
NA Test 1.00 0.1 0.01
2 Test 2.00 0.2 0.02
3 Test 3.00 0.3 0.03
If I can provide any more informations, please comment and I will try to provide what I can. Thanks for the help.
Edit: Ok, thx for the discussion so far. I understand (and knew already before) that this is not the super best way to do this, because it is much slower than a functional approach but execution time is not important in this case. A work-around has been provided in the comments by @MrFlick, by just renaming the row.names at the end (rownames(df)<-1:nrow(df)
). Anyway this helps, but it still feels unsatisfying to me since it doesn't treat the cause but only deals with the symptoms.