我有一个包含两个变量的数据集,我希望统计测试它们在引导循环中是否相关(即使用 Spearman 的等级校正cor.test(...)
).
我的数据集中的大多数测量值都来自独立的样本单位(我们称之为植物单位),尽管有些测量值来自同一植物。为了处理伪复制问题,我希望多次引导统计测试,在每次测试运行中仅使用每个植物的一个测量值。因此,我需要编写一个引导循环,在执行相关性测试之前,为每个植物随机绘制一个测量值(然后重复此过程 99 次)。
我希望最终得到一个 csv 文件,其中包含 99 个测试中每个测试的 p 值、rho 和 S 统计量。
示例数据:
dput(df)
structure(list(Plant = c(1L, 2L, 3L, 4L, 5L, 6L, 6L, 7L, 8L,
9L, 10L, 10L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 18L,
19L, 20L, 21L), Length = c(170L, 232L, 123L, 190L, 112L, 207L,
93L, 291L, 178L, 206L, 141L, 257L, 304L, 222L, 279L, 192L, 101L,
253L, 176L, 278L, 311L, 129L, 191L, 205L, 226L), Count = c(7L,
9L, 5L, 7L, 5L, 6L, 2L, 10L, 6L, 7L, 4L, 8L, 11L, 7L, 8L, 5L,
5L, 9L, 7L, 6L, 9L, 4L, 5L, 7L, 6L)), .Names = c("Plant", "Length",
"Count"), class = "data.frame", row.names = c(NA, -25L))
Plant Length Count
1 1 170 7
2 2 232 9
3 3 123 5
4 4 190 7
5 5 112 5
6 6 207 6
7 6 93 2
8 7 291 10 etc....
到目前为止,我已经整理了下面的代码,首先为由多行表示的每种植物随机绘制一行,并在运行统计测试之前将这些值与其余数据组合起来。然而,我现在正在努力整合引导功能(即boot()
or bootstrap()
) 运行统计测试并多次执行循环:
# 1. create dataframe without plants with >1 measurement/row (in this example plant 6,10 & 18 have multiple rows)
df_uniq = df[ ! df$Plant %in% c(6,10,18), ]
# 2. create data subsets for each plant with >1 measurement/row
dup1 = df[6:7,]
dup2 = df[11:13,]
dup3 = df[21:22,]
# 3. randomly draw one row for each plant with multiple measurements
d1_draw = dup1[sample(nrow(dup1), 1), ]
d2_draw = dup2[sample(nrow(dup2), 1), ]
d3_draw = dup3[sample(nrow(dup3), 1), ]
# 4. merge df_uniq with randomly drawn rows for each plant with multiple measurements
df_merge = rbind(df_uniq, d1_draw, d2_draw, d3_draw)
# 5. Test whether the two variables (length & Count) are related and write results to file
cor_res <- cor.test(df_merge$Length, df_merge$Count, method= "spearman")
write.csv(matrix(c(cor_res$statistic, cor_res$p.value, cor_res$estimate)), row.names=c("statistic", "p.value", "rho"), "test_output.csv")
我确信有一种快速而优雅的方法来解决这个问题。任何帮助将不胜感激!非常感谢。