我正在寻找循环中rbind.fill
数据帧的方法。我想要的结果如下:
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)
我需要创建一个循环,自动将字符串作为新行添加到多个数据帧。这是一个例子:
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]))
}
如您所见,数据框(df1
,df2
和df3
)不包含其他行。如何解决这个问题?请记住,我想永久地向旧dfs添加行,以便稍后我可以编写它们。
重要提示:它必须是rbind.fill
函数或任何其他方法,用不同列号的行绑定数据帧。
答案 0 :(得分:2)
您可以将所有数据框放在列表中并应用,即
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)})