0

我有一个按物种矩阵排列的站点,如下所示:

colA= c("A","A","A","B","B","B","C","C","C")
colB= c(1,2,3,3,0,1,2,1,0)
colC= c(0,0,0,1,0,0,0,0,1)
df= data.frame (site=colA, sp1=colB, sp2=colC)

该矩阵具有三个站点 A、B、C 和两个物种 sp1、sp2。

我正在尝试构建代码,按站点汇总每个物种的丰度。最终输出应该是一个数据框,其中一列包含站点,第二列包含物种名称,第三列包含该站点该物种的丰度。

我猜这必须在每个站点的循环中完成,然后将摘要放入新的数据框中。

输出应如下所示:

colA= c("A","B","C","A","B","C")
colB= c("sp1","sp1","sp1","sp2","sp2","sp2")
colC= c(6,4,3,0,1,1)
output= data.frame (site=colA, species=colB, abundance=colC)
output
4

1 回答 1

3

我猜你想要这个:

res <- aggregate(cbind(sp1,sp2)~site, df, sum)
library(reshape2)
melt(res)
#   site variable value
# 1    A      sp1     6
# 2    B      sp1     4
# 3    C      sp1     3
# 4    A      sp2     0
# 5    B      sp2     1
# 6    C      sp2     1
于 2013-10-09T13:35:29.393 回答