I am trying to append rows to a dataframe inside a user defined function. I have done this before in a for loop without difficulty, as follows:
t1 <- data.frame(a=character(),
b=numeric())
for(i in 1:2){
tmp.df <- data.frame(a="apple", b=i)
t1 <- rbind(t1,tmp.df)
}
I get a dataframe with two observations.
But when I try and do a similar thing inside a function, it doesn't work. I have tried debugging the function and at the rbind step it just seems to exit the function without carrying out that step. So the following code ends up with the original empty data frame.
t1 <- data.frame(a=character(),
b=numeric())
create.rows <- function(id, it){
if(it==1){
tmp.df <- data.frame(a=id, b=it)
t1 <- rbind(t1,tmp.df)
}else{
tmp.df <- data.frame(a=id, b=99)
t1 <- rbind(t1,tmp.df)
}
}
Why is this happening and what can I do to fix it?
Note that I do not know in advance how many rows there will be in the dataframe so I can't write directly to a particular row.