首页 > 解决方案 > 在 R 中创建一个数据框列,该列指示每行值被采样了多少次

问题描述

我正在使用 R 从包含 36 个元素的向量中抽取 24 个元素(物种)的随机样本。由于我必须多次重复这个过程,我想创建一个数据框,其中第一列是物种的名称,第二列是物种被采样次数的计数器。所以,在第一次采样结束时,我会有类似的东西:

   Plot_1                      Freq
   Agrostis castellana         1
   Amaranthus hybridus         1
   Ambrosia artemisiifolia     1
   Bromus secalinus            0
   ...                         ...

然后,在第二次提取后,我会

   Plot_1                      Freq
   Agrostis castellana         2      #extracted both in Plot1 and Plot2
   Amaranthus hybridus         1      #extracted only in either Plot1 or Plot2
   Ambrosia artemisiifolia     1
   Bromus secalinus            0      #not extracted yet
   ...                         ...

我在互联网上查看过,但似乎找不到解决方案:(请帮忙!非常感谢!!

标签: rrandomcounter

解决方案


让我们举一个小例子:

#convert your vector into factor
species <- factor(letters)
#Iteration 1
tab <- stack(table(sample(species, n)))

repeat_sample <- function(df, x, n) {
   tab <- stack(table(sample(x, n)))
   tab[1] <- tab[1] + df[1]
   return(tab)
}

#Iteration 2
tab <- repeat_sample(tab, species, 15)


#   values ind
#1       0   a
#2       1   b
#3       1   c
#4       0   d
#5       0   e
#6       1   f
#7       1   g
#8       2   h
#9       1   i
#10      0   j
#....

#Iteration 3
tab <- repeat_sample(tab, species, 15)

替换species为您拥有的向量,并将 15 替换为您要绘制的样本数,即 24。


推荐阅读