r - 在 R : subsets of unequal length 中处理 tapply() 与 ddply {plyr} 的输出

标签 r subset plyr

我有一个数据框:

> df <- data.frame(
+   Species = rep(LETTERS[1:4], times=c(5,6,7,6)),
+   Length = rep(11:14, each=3) 
+ )
> 
> df

我需要能够计算每个物种特定长度的个体数量(即,物种 A 中有多少个体的长度为 1、2、3 等?)然后,我需要对输出执行一系列附加分析。例如,我需要计算每个长度的个体密度,以及从一个长度等级到下一个长度等级的密度降低。

如果我先对数据进行子集化,这很容易:

Spec.A<-df[df$Species=="A",] 

#count number of specimens of each length; 
count<-table(Spec.A$Length)
count

#calculate density per length category (divide by total area sampled =30) 
density<-count/(30)
density

#calculate the decrease in density (delta.N) from one length category to the next; 
delta.N<-diff(density, lag=1, differences=1)
delta.N

问题是我需要对每个物种进行这些计算(即遍历每个子集)。

一方面,我可以使用 tapply(),以及一个使用 table() 的函数;

#function: count number of specimens of each length; 
count<-function(x){
table(x)
}

Number<-tapply(df$Length, df$Species, FUN=count, simplify=FALSE)
Number

这给了我想要的,但输出的格式很奇怪,我不知道如何对结果进行额外的分析。

我试过使用 plyr 中的 ddply(),比如:

ddply(df$Length, df$Species,
count)

但我显然没有做对,而且我什至不确定 ddply() 是否适合我的问题,因为我对每个物种的长度观测值不同。

我应该更仔细地查看 plyr 中的其他选项吗?或者有没有办法编写一个 for 循环来完成我需要的事情?

最佳答案

您走在正确的轨道上! tapply 与列表输出绝对是一种方式,并且可能是一个不错的选择,因为您的输出将具有不同的长度。

ddply,如您所料,是另一种方式。关键是你给 ddply 的函数的输出应该是一个数据框,你的所有统计数据都处于“长”模式(这样它们就会很好地堆叠)。简单的 count 函数无法做到这一点,因此您需要创建自己的函数。我为这样的 ddply 调用设计函数的方式实际上与您所做的非常相似:我获取数据的一个子集,然后使用它来制作我的函数。然后,当您将它提交给 ddply 时,它会很好地将该函数应用于所有子集。

SpeciesStats <- function(df) {
  counts    = table(df$Length)
  densities = counts/30
  delta.N   = diff(densities, lag=1, differences=1)

  data.frame(Length   = names(counts),
             Count    = as.numeric(counts),
             Density  = as.numeric(densities),
             delta.N  = c(NA, delta.N), 
             row.names=NULL)
}
> ddply(df, 'Species', SpeciesStats)
   Species Length Count    Density     delta.N
1        A     11     3 0.10000000          NA
2        A     12     2 0.06666667 -0.03333333
3        B     12     1 0.03333333          NA
4        B     13     3 0.10000000  0.06666667
5        B     14     2 0.06666667 -0.03333333
6        C     11     3 0.10000000          NA
7        C     12     3 0.10000000  0.00000000
8        C     14     1 0.03333333 -0.06666667
9        D     13     3 0.10000000          NA
10       D     14     3 0.10000000  0.00000000

关于r - 在 R : subsets of unequal length 中处理 tapply() 与 ddply {plyr} 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7985154/

相关文章:

r - 将标签添加到 R 中的剪切功能

r - ggplot2 中 X 轴变量标签上的真正减号

python - Pandas 在数据帧子集上设置行值

r - 在两个数组之间划分特定值

r - 使用 dplyr 的 rename() 包括不在数据集中的变量名称

r - 我无法计算出 TraMineR 的熵公式

r - 与 R 中的plot3D包重叠标签

r - 使用子集创建高效的每周计算

r - 具有 2 个条件的子集不适用于哪个功能

r - 在 R w/PLYR 中提取组回归系数