以下是我遇到问题的示例数据和部分功能。
# 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))