如何根据索引号对数据框中的列求和?

时间:2012-07-29 15:57:49

标签: r statistics

我有许多dbf表(来自不同程序中的分析的输出)需要读入R并进行汇总。每个dbf都有许多列,代表不同的边缘或核心栖息地类。根据以前的分析,不同的dbf文件将具有不同数量的核心和边缘类(列),因此我不能简单地在一致的索引值范围内求和,例如[2:4]。

为了确定存在哪些列(用于求和)以及这些列的索引号,我编写了以下循环。这将根据主列表(ae)检查当前表名称,如果列存在,则获取当前数据框中列的索引号:

#read in all the possible edge column names
    ae<-c("VALUE_1","VALUE_3","VALUE_5","VALUE_9","VALUE_33","VALUE_35","VALUE_37","VALUE_65","VALUE_67","VALUE_69","VALUE_101","VALUE_103","VALUE_105","VALUE_109","VALUE_133","VALUE_135","VALUE_137","VALUE_165","VALUE_167","VALUE_169")

#Create and empty data frame and turn off stringsAsFactors:
options(stringsAsFactors=FALSE)
edgeIndices<-data.frame()

#for each column name, get the index number 
for (i in ae) {
  index<-which(colnames(currfile)==i)

  #check to see if ae is in currfile
  #if it is, get the index number, if not skip ahead
  if (length(index)>0){ edgeIndices<-rbind(edgeIndices,c(index, i)) }
  else {}
}

#for some reason the index number is coming in as a character
#also, I need to figure out how to bring in the label without 
# it forcing to factor (I     have changed the global parameter for now)

#name the columns
names(edgeIndices)=c("Index","Label")

#change the index to a number:
edgeIndices$Index<-as.numeric(edgeIndices$Index)

这是我的输出:

  Index   Label
1 3       VALUE_1
2 4       VALUE_3
3 5       VALUE_9
4 7       VALUE_33
5 8       VALUE_35
6 9       VALUE_65
7 10      VALUE_67
8 12      VALUE_101

所以,现在我的问题是,如何将索引值传递给rowSums()函数,以便只将具有相应索引#的列相加?

例如,在下面的情况中,只应将值1,3和9相加,这将是指数3,4和5

OID_    VALUE_0 VALUE_1 VALUE_3 VALUE_9 SUM
4473    181800  15300   200700  0   216000
4474    239400  6300    153000  0   159300
4475    296100  13500   86400   0   99900

0 个答案:

没有答案