在 R 中,当您不知道所有数据集中有多少列时如何提取列?

In R, How do you extract columns when you don't know how many columns there are in all datasets?

我有一个包含 52 个数据集的列表,我正在尝试从每个数据集中获取指定数量的列的列总和,并将其导出到新的数据框。我知道我想对第 9 列及之后的所有内容求和,但每个数据集的总列数各不相同。 (“locs”是我的数据框列表)

这是我使用 for 循环尝试过的方法:

summaryofsums <- vector("list",1) #empty vector

for (df in 1:length(locs)){
  newdf <- df[, colSums(df!= 0) > 0] #get rid of all columns that have only 0s
  newdfsum <- colSums(newdf[,9:length(newdf)])  
  summaryofsums[i] <- newdfsum
}

我收到以下错误:

Error in colSums(df != 0) : 
  'x' must be an array of at least two dimensions

version _
platform x86_64-apple-darwin15.6.0
arch x86_64
os darwin15.6.0
system x86_64, darwin15.6.0
status
major 3
minor 5.3
year 2019
month 03
day 11
svn rev 76217
language R
version.string R version 3.5.3 (2019-03-11) nickname Great Truth

谢谢!!

我注意到的第一件事是,您正在对列表执行 1:length(),但没有调用该列表中的项目,例如,以您希望的方式调用:

for(i in 1:length(locs)){
 locs[[i]] #where this is now df in your code
 ....
}

我认为更简单的方法是:

 # Create your (I assume) variable to hold your sums
 0 -> summaryofsums
 
 # Loop through each dataframe and get the sum of everything after 9th column
 # This will produce a list with each entry the sum of each column after 9 per
 # dataframe
 for(df in locs){
  df[, colSums(df) > 0] -> newdf
  sum(colSums(newdf[, 9:ncol(newdf)])) + summaryofsums -> summaryofsums
  }
  

这将简单地创建一个变量 summaryofsums,它是所有数据集中第 9 列之后所有列中所有值的总和。

使用sapply

sapply(locs, function(df) {
  newdf <- df[, colSums(df!= 0, na.rm = TRUE) > 0]
  colSums(newdf[,9:ncol(newdf)], na.rm = TRUE)  
}) -> result

result