下面是示例数据和我有问题的部分功能。
# 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个数据格式,这样我就不需要编写冗长的步骤了:
请注意,其中的每个数据文件都有相同的变量名称。对于每个组件dataframe,我希望执行以下任务。如果我不做循环的话:
# 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))发布于 2012-07-09 16:19:51
我可能离这里很远,但是
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 ...可能是你所追求的.
编辑:更改为希望生成数据格式
感谢乔恩
https://stackoverflow.com/questions/11398318
复制相似问题