首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在r中的列表组件中应用循环,在r中应用绑定列表组件。

在r中的列表组件中应用循环,在r中应用绑定列表组件。
EN

Stack Overflow用户
提问于 2012-07-09 15:32:43
回答 1查看 489关注 0票数 1

下面是示例数据和我有问题的部分功能。

代码语言:javascript
复制
# 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,我希望执行以下任务。如果我不做循环的话:

代码语言:javascript
复制
# 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))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-09 16:19:51

我可能离这里很远,但是

代码语言:javascript
复制
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 ...

可能是你所追求的.

编辑:更改为希望生成数据格式

感谢乔恩

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11398318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档