以下是我遇到问题的示例数据和部分功能。
# data
Gr1 <- data.frame (group = rep(1:2, each = 2001),
position = round (c(0, cumsum (rnorm (2000, 0.05, 0.08)), 0,
cumsum (rnorm (2000, 0.05, 0.08)))))
Gr2 <- data.frame (group = rep(1:2, each = 2001),
position = round (c(0, cumsum (rnorm (2000, 0.05, 0.08)), 0,
cumsum (rnorm (2000, 0.04, 0.08)))))
Gr3 <- data.frame (group = rep(1:2, each = 2001),
position = round (c(0, cumsum (rnorm (2000, 0.05, 0.08)), 0,
cumsum (rnorm (2000, 0.05, 0.08)))))
groupobs = list(Gr1, Gr2, Gr3)
grnames = c("A", "B", "C")
spacing = c(0, 0.1, 0.3)
# for loop
for (i in 1:length(groupobs)){
groupobs[i]$sgrp <- grnames[i]
groupobs[i]$y <- groupobs[i]$group + spacing[i]
}
# binding of list components
mydf <- data.frame (rbind (groupobs)
我怎样才能做到这一点?
编辑:通过上述循环,我想实现以下手动过程。我想自动化n个数据帧,因此我不需要编写冗长的步骤:
请注意,其中的每个数据框都具有相同的变量名称。对于每个组件数据帧,我想执行以下任务。如果我这样做而没有循环:
# for first dataframe with in list
Gr1$sgrp <- grnames[1]
Gr1$y <- Gr1$group + spacing[1]
# for second dataframe in the list
Gr2$sgrp <- grnames[2]
Gr2$y <- Gr1$group + spacing[2]
# for third dataframe in the list
Gr3$sgrp <- grnames[3]
Gr3$y <- Gr1$group + spacing[3]
mydf <- data.frame (rbind (Gr1, Gr2, Gr3))
答案 0 :(得分:3)
我可能会离开这里,但是
mydf<-mapply(function(a,b,c){a$sgrp<-b;a$y<-c;a},groupobs,grnames,spacing,SIMPLIFY = F)
mydf<-do.call("rbind",mydf)
> str(mydf)
'data.frame': 12006 obs. of 4 variables:
$ group : int 1 1 1 1 1 1 1 1 1 1 ...
$ position: num 0 0 0 0 0 0 0 0 0 1 ...
$ sgrp : chr "A" "A" "A" "A" ...
$ y : num 0 0 0 0 0 0 0 0 0 0 ...
可能就是你所追求的.............
编辑:改为希望生成数据框
感谢@jon