R:如何在循环中绑定嵌套循环的所有数据帧的特定列? [英] R: How can I cbind specific columns of all data frames of a nested loop within the loop?

查看:70
本文介绍了R:如何在循环中绑定嵌套循环的所有数据帧的特定列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在同一循环过程中合并几个数据帧的第三列,这些数据帧在嵌套的for循环中被调用和重命名.

I am trying to combine the third column of several data frames, which are called and renamed in a nested for loop, within the same looping process.

# Sample Data
ecvec_msa6_1998=matrix( round(rnorm(200, 5,15)), ncol=4)
ecvec_msa6_1999=matrix( round(rnorm(200, 4,16)), ncol=4)
ecvec_msa6_2000=matrix( round(rnorm(200, 3,17)), ncol=4)

datasets=c("msa")
num_industrys=c(6)
years=c(1998, 1999, 2000)

alist=list() 

for (d in 1:length(datasets)) {
  dataset=datasets[d]
  for (n in 1:length(num_industrys)){
    num_industry=num_industrys[n]
    for (y in 1:length(years)) {
      year=years[y]

     eval(parse(text=paste0("newly_added = ecvec_", dataset, num_industry, "_",  year))) 
     # renaming the old data frames

     alist = list(alist, newly_added) # combining them in a list

     extracted_cols <- lapply(alist, function(x) x[3]) # selecting the third column

     result <- do.call("cbind", extracted_cols) # trying to cbind the third colum

    }
  }
}

有人可以告诉我正确的方法吗?

Can somebody show me the right way to do this?

推荐答案

您的代码几乎可以正常工作-这里有一些更改...

Your code almost works - here are a few changes...

alist=list() 

for (d in 1:length(datasets)) {
  dataset=datasets[d]
  for (n in 1:length(num_industrys)){
    num_industry=num_industrys[n]
    for (y in 1:length(years)) {
      year=years[y]
      eval(parse(text=paste0("newly_added = ecvec_", dataset, num_industry, "_",  year)))                                   
      #the next line produces the sort of list you want - yours was too nested
      alist = c(alist, list(newly_added))
    }
  }
}

#once you have your list, these commands should be outside the loop          
extracted_cols <- lapply(alist, function(x) x[,3]) #note the added comma!
result <- do.call(cbind, extracted_cols) #no quotes needed around cbind

head(result)
     [,1] [,2] [,3]
[1,]   11   13   24
[2,]  -26   -3    7
[3,]   -1  -26  -14
[4,]    5   14  -15
[5,]   28    3    8
[6,]    9   -9   19

但是-一种更像R的(并且更快)的方法是用

HOWEVER - a much more R-like (and faster) way of doing this would be to replace all of the above with

df <- expand.grid(datasets,num_industrys,years) #generate all combinations
datanames <- paste0("ecvec_",df$Var1,df$Var2,"_",df$Var3) #paste them into a vector of names
result <- sapply(datanames,function(x) get(x)[,3])

sapply会自动将列表简化为数据框(lapply始终生成列表)

sapply automatically simplifies the list into a dataframe if it can (lapply always produces a list)

这篇关于R:如何在循环中绑定嵌套循环的所有数据帧的特定列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆