在 R 中创建一个数据框列,指示每个行值被采样的次数
Create in R a dataframe column that indicates how many times each row value has been sampled
我正在使用 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。
我正在使用 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。