4

如何使用 R 查找物种值的总和?我有 62 个物种名称,想为栖息地中的每个物种添加基础面积。我试过了

aggregate(file name, species, FUN=sum, simplify=TRUE)

以及对此的许多变体,但它总是说它找不到species(我的数据集中的列标题)。列表太长,无法添加为输入;我希望程序使用我的专栏信息。我的数据集如下所示:

Species      BA
sp1          0.5
sp1          0.2
sp2          0.1
4

2 回答 2

5

首先将数据读入数据框,然后使用聚合。

# You would read from the file instead.
x <- read.table(header=T, file=textConnection("Species      BA
sp1          0.5
sp1          0.2
sp2          0.1
"))

> aggregate(.~Species, data=x, FUN=sum)
  Species  BA
1     sp1 0.7
2     sp2 0.1
于 2012-12-02T21:19:57.737 回答
4

这个data.table包非常适合这种东西。

首先,加载包并创建一些数据。

library(data.table)
set.seed(1)
dat <- data.table(Species = paste("s", sample(1:3, 15, replace = TRUE), sep = ""),
                  BA = rnorm(15), CA = rnorm(15), DA = rnorm(15), EA = rnorm(15),
                  key="Species")
dat
#     Species           BA          CA         DA          EA
#  1:      s1 -0.005767173  0.80418951  1.2383041 -0.79533912
#  2:      s1 -1.147657009 -0.69095384 -0.4527840 -0.17262350
#  3:      s1 -0.891921127 -0.43331032  1.1565370 -0.94064916
#  4:      s1  0.435683299 -0.64947165  0.8320471 -0.11582532
#  5:      s1 -1.237538422  0.72675075 -0.2273287 -0.81496871
#  6:      s2  2.404653389 -0.05710677 -0.2793463 -0.05487747
#  7:      s2  0.763593461  0.50360797  1.7579031  0.25014132
#  8:      s2 -0.411510833 -0.23570656 -1.0655906  0.35872890
#  9:      s2  0.252223448 -0.54288826 -1.5637821 -0.01104548
# 10:      s2  0.377395646  0.99216037 -0.3767027 -1.42509839
# 11:      s3 -0.799009249  1.08576936  0.5607461  0.61824329
# 12:      s3 -0.289461574 -1.28459935 -0.8320433 -2.22390027
# 13:      s3 -0.299215118  0.04672617 -1.1665705 -1.26361438
# 14:      s3 -0.224267885  1.15191175  0.2661374  0.24226348
# 15:      s3  0.133336361 -0.42951311  2.4413646  0.36594112

注意:如果你已经有一个data.frame(我想你有),你可以使用data.table(YourDataFrame, key=YourGroupingColumns)

这是实际的聚合。.SD是数据列的子集。默认情况下,这是您数据中除keys 之外的所有列(您的分组列;在这种情况下,我们将“Species”指定为我们的键)。

dat[, lapply(.SD, sum), by=key(dat)]
#    Species        BA         CA        DA         EA
# 1:      s1 -2.847200 -0.2427955  2.546776 -2.8394058
# 2:      s2  3.386355  0.6600668 -1.527519 -0.8821511
# 3:      s3 -1.478617  0.5702948  1.269634 -2.2610668

但是,还有一个.SDcols参数可让您通过名称或数字索引指定您感兴趣的列。

dat[, lapply(.SD, sum), by=key(dat), .SDcols = "DA"]
#    Species        DA
# 1:      s1  2.546776
# 2:      s2 -1.527519
# 3:      s3  1.269634
dat[, lapply(.SD, sum), by=key(dat), .SDcols = 2:3]
#    Species        BA         CA
# 1:      s1 -2.847200 -0.2427955
# 2:      s2  3.386355  0.6600668
# 3:      s3 -1.478617  0.5702948
# or perhaps, more easily understood.
dat[, lapply(.SD, sum), by=key(dat), .SDcols = c('BA','CA')]
#    Species        BA         CA
# 1:      s1 -2.847200 -0.2427955
# 2:      s2  3.386355  0.6600668
# 3:      s3 -1.478617  0.5702948
于 2012-12-03T02:20:46.667 回答