本文介绍了将分离的物种数量数据处理到物种丰度矩阵中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人可以为R中的某些数据处理提供帮助,因为当前数据的格式有些奇怪,所以我一直在努力使其工作。

I was hoping somebody could help with some data manipulation in R, i'm struggling to get this to work as the data is currently in a slightly odd format.

我需要一个物种丰富度表才能在素食主义者中运行某些功能。

I need a species abundance table in order to run some of the functions in vegan.

但是,当我收集数据时,我用不太兼容的方式输入了数据因为我必须从同一站点收集的物种按日期和其他因素分开,这对于另一个程序来说是必需的。

However when I collected the data I inputted it in a way which is not very compatable as I had to keep species collected from the same site seperated by date and other factors which was necessary for another program.

所以我的数据目前看起来像这样:

So my data currently looks like this:

df <- data.frame (Site=c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
species=c("a","a","a","b","b","c","a","b","b","b","c","d","a","b","c","f","f","f"),
Quantity=c(3,1,1,2,3,3,5,12,1,2,4,1,5,6,3,1,1,1))

我试图操纵它的是一个丰度矩阵,例如:

And what i'm trying to manipulate it to is an abundance matrix, so like:

colA= c(1,2,3)
colB=c(5,5,5)
colC=c(5,15,6)
colD=c(3,4,3)
colE=c(0,1,0)
colF=c(0,0,1)
colG=c(0,0,2)
df= data.frame (site=colA, SpeciesA=colB, SpeciesB=colC,SpeciesC=colD,SpeciesD=colE,SpeciesE=colF,SpeciesF=colG)

我的第一个计划是为每个站点循环,然后为站点内的每个分类单元进行第二个循环,然后我将每个分类单元的数量总和绑定到数据表中,问题出在我最终会有很多表,每个站点的列数不同,然后不能将它们绑定在一起。

My first plan was to loop through for each site, then a second loop for each taxon within a site, i would then take the sum of the quantity for each taxa and cbind it into a data table, the problem occurs as I end up with lots of tables with different numbers of columns for each site, which then cant be bound together into one.

任何帮助或建议将不胜感激。

Any help or suggestions would be very much appreciated.

非常感谢。

推荐答案

library(reshape2) 
res <- dcast(df, Site~species, value.var="Quantity", sum)
 colnames(res) <- c("site", paste0("Species", LETTERS[c(1:4,6)]))
 res
 #   site SpeciesA SpeciesB SpeciesC SpeciesD SpeciesF
 # 1    1        5        5        3        0        0
 # 2    2        5       15        4        1        0
 # 3    3        5        6        3        0        3

这篇关于将分离的物种数量数据处理到物种丰度矩阵中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 09:58