首页 > 解决方案 > 在 R 中,当您不知道所有数据集中有多少列时,如何提取列?

问题描述

我有一个包含 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) 昵称伟大的真理

谢谢!!

标签: rsumextractmultiple-columns

解决方案


使用sapply

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

result

推荐阅读