r - 在 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
... ...
我在互联网上查看过,但似乎找不到解决方案:(请帮忙!非常感谢!!
解决方案
让我们举一个小例子:
#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。
推荐阅读
- java - 如何在具有不同ID的字符串xml android中查找重复的字符串?
- stripe-payments - 我如何知道 Stripe 付款是否用于测试?
- c++ - (C++) 查找两个整数之间的所有素数(不使用 Eratosthanes 筛)
- javascript - Javascript 动画(Canvas)不能在 Firefox、Edge 上工作,但可以在 Chrome 上工作
- javascript - 在 asp.net 中的 javascript/jquery 中访问服务器端变量
- ios - 从 2018-10-23T06:01:10.806Z 转换为 10-May-2018 和一个单独的时间字符串
- sql - 如何避免在sql server中选择具有特殊符号的行
- android - 通过 Firebase 中的 JAVA 动态克隆/复制和填充 Layout 中的数据 - Android
- amazon-rds - 自动执行 - 在 rds 参数组中应用更改,重新启动 rds,然后应用另一个更改
- c# - 构建docfx后PlantUml不渲染图表