Alexandros
Alexandros

Reputation: 333

adding new rows in a loop with rbind.fill

Im looking of a way to rbind.fill data frames in a loop. My desired result looks like this:

library(plyr)
set.seed(101)
df1=data.frame("var1"=runif(18,min=0,max=1),
              "index2"=c(rep(c("A","B","C"),6)),
              "index1"=c(rep(1,9),rep(2,9)))
x=df1[,1]+10
new_variable=data.frame(var1=x)
rbind.fill(df1,new_variable)

I need to make a loop that automatically add a string as new rows to multiple data frames. Here is an example:

library(plyr)
#to be sure everyone has same output
set.seed(101)
#example dfs
df1=data.frame("var1"=runif(18,min=0,max=1),
              "index2"=c(rep(c("A","B","C"),6)),
              "index1"=c(rep(1,9),rep(2,9)))


df2=data.frame("var1"=runif(18,min=0,max=1),
               "index2"=c(rep(c("A","B","C"),6)),
               "index1"=c(rep(1,9),rep(2,9)))

df3=data.frame("var1"=runif(18,min=0,max=1),
               "index2"=c(rep(c("A","B","C"),6)),
               "index1"=c(rep(1,9),rep(2,9)))

#df names
df.names=c("df1","df2","df3")

#loop
for (i in 1:length(df.names)){
  x=get(df.names[i])[,1]+10
  new_variable=data.frame(var1=x)
  #my idea of what binding code should look like
  rbind.fill(get(df.names[i]),new_variable)
  #to print results
  print(get(df.names[i]))
  }

As you can see data frames (df1, df2 and df3) does not contain additional rows. How to fix this? Keep in mind I want add rows to old dfs permanently so I can later write them.

Important note: it has to be rbind.fill function or any other method that binds data frames by rows with different column numbers.

Upvotes: 0

Views: 247

Answers (1)

Sotos
Sotos

Reputation: 51592

You can put all data frames in a list and apply, i.e.

library(plyr)

l1 <- mget(ls(pattern = 'df[0-9]+'))
l1 <- lapply(l1, function(i){m1 <- i[1] + 10; 
                       new_vars <- data.frame(var1 = m1); 
                       rbind.fill(i, new_vars)})

Upvotes: 2

Related Questions