对于指定列的数据表的行进行求和 [英] Summing across rows of a data.table for specifc columns

查看:173
本文介绍了对于指定列的数据表的行进行求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大型数据表(从包中数据。表格),其中超过60列(前三个对应于因子,剩余的对应于响应变量,在这种情况下是不同的物种)和几行,对应于不同的处理水平和物种丰度。
一个非常小的版本如下:

I have a large data table (from the package data.table) with over 60 columns (the first three corresponding to factors and the remaining to response variables, in this case different species) and several rows corresponding to the different levels of the treatments and the species abundances. A very small version looks like this:

>library(data.table)
> TEST<-data.table(Time=c("0","0","0","7","7","7","12"),
             Zone=c("1","1","0","1","0","0","1"),
             quadrat=c(1,2,3,1,2,3,1),
             Sp1=c(0,4,29,9,1,2,10),
             Sp2=c(20,17,11,15,32,15,10),
             Sp3=c(1,0,1,1,1,1,0))

>setkey(TEST,Time)

> TEST
    Time Zone quadrat Sp1 Sp2 Sp3
1:    0    1       1   0  20   1
2:    0    1       2   4  17   0
3:    0    0       3  29  11   1
4:   12    1       1  10  10   0
5:    7    1       1   9  15   1
6:    7    0       2   1  32   1
7:    7    0       3   2  15   1  

我首先想要计算每个区域x样方组合的每个物种的平均丰度,这很好:

I first want to calculate the mean abundances of each species across Time for each Zone x quadrat combination and that's fine:

> Abundance = TEST[,lapply(.SD,mean),by="Zone,quadrat"]
> Abundance
   Zone quadrat Time       Sp1  Sp2       Sp3
1:   Z1       1   NA  6.333333 15.0 0.6666667
2:   Z1       2   NA  2.500000 24.5 0.5000000
3:   Z0       1   NA 15.500000 13.0 1.0000000  

但是,我想对species列的每一行进行求和,例如从Sp1到Sp3。我试过下面的代码没有成功:

But then I want to sum across each row for the 'species' columns, in the example from Sp1 to Sp3. I have tried the following code with no success:

 > Abundance$SumAbundance <- rowSums(Abundance[,c(4:6)])  



错误消息:

rowSums中的错误(Abundance [,c(4:6)]):
'x'必须是至少两个维度的数组

I get the error message:
Error in rowSums(Abundance[, c(4:6)]) : 'x' must be an array of at least two dimensions

这只是我需要对这些数据进行一系列计算的第一步,所以任何帮助将非常感谢。感谢

This is just the first step to a series of calculation I need to do with this data so any help would be greatly appreciated. Thanks

推荐答案

实际输入 Abundance [,c(4:6)] 看看结果是什么,它会清楚为什么,没有工作。它可以通过使用 with = FALSE 来更正,但更好的语法(少复制)是:

Actually type Abundance[, c(4:6)] to see what the result is and it'll be clear to you why that didn't work. It can be corrected by using with = FALSE, but the better syntax (with less copying) is:

Abundance[, SumAbundance := rowSums(.SD), .SDcols = 4:6]


b $ b

此外,我没有检查,但我有一个怀疑,这将更快,因为它不会转换为 matrix as rowSums 会:

Abundance[, SumAbundance := Reduce(`+`, .SD), .SDcol = 4:6]

这篇关于对于指定列的数据表的行进行求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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