1

以下是我遇到问题的示例数据和部分功能。

# 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))
4

1 回答 1

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

于 2012-07-09T16:19:51.430 回答