(我是新手,所以现在编辑我的问题作为一个可重复的例子)。我已经回顾了自举,循环和复制函数,并且无法弄清楚如何在R中重复一系列步骤(不仅仅是单个函数)并将结果存储在数据帧中。我需要从22个值的池中随机选择2个值,9次。然后对该数据集(2列,9行)进行10,000次spearman等级相关性测试,并存储每次迭代的值。所以我需要在10,000次以下重复这些步骤并存储每个spearman等级结果。
#For each isotope (C,N,S) obtain two samples of nine individuals extracted
#at random from the pool of the studied population, n = 22 nestlings) and
#compare their isotopic values with a Spearman rank correlation.
# take a random sample of size 2 (9 times) from a dataset mysample
# sample without replacement
c13 = c(-25.12,-20.95,-23.98,-23.78,-25.45,-26.27,-11.13,-12.75,-18.77,-18.38,-16.65, -16.96,-16.71,-19.57,-20,-23.19,-17.38,-17.83,-18.86,-18.71,-25.57,-21.9)
n15 = c(10.22,12.64,11.06,10.81,11.55,11.28,16.37,16.17,13.52,13.83,14.27,14.07,14.25,13.09, 12.59,11.42,13.97,13.77,14,15.21,11.73,11.8)
s34 = c(4.61,12.35,5.19,5.54,5.2,5.12,14.42,14.56, 12.78,13.11,18.78,18.71,19.19,11.58,11.08,7.89,17.51,17.34,12.55,12.65,6.42,8.49)
df = data.frame(c13,n15,s34)
mysample< - matrix(sample(c13,18),ncol = 2)
#mysample是一个向量 is.atomic(MYSAMPLE)
#Convert转向数据帧以进行相关性测试。 mysample< - as.data.frame(mysample) is.atomic(MYSAMPLE)
#name列 colnames(mysample)< - c(" siblingcarbon1"," siblingcarbon2")
#Conduct对这些随机选择的值进行Spearman等级相关性测试 cor.test(mysample $ siblingcarbon1,mysample $ siblingcarbon2,method =" spearman")
#对于c13重复先前的过程10,000次,并为每次运行存储Spearman等级值(不确定如何执行此操作)
答案 0 :(得分:0)
根据您的修改更新答案:
c13 = c(-25.12, -20.95, -23.98, -23.78,-25.45, -26.27, -11.13, -12.75, -18.77, -18.38, -16.65, -16.96, -16.71, -19.57, -20, -23.19, -17.38, -17.83, -18.86, -18.71, -25.57, -21.9)
n15 = c(10.22, 12.64, 11.06, 10.81, 11.55, 11.28, 16.37, 16.17, 13.52, 13.83, 14.27, 14.07, 14.25, 13.09, 12.59, 11.42, 13.97, 13.77, 14, 15.21, 11.73, 11.8)
s34 =c (4.61, 12.35, 5.19, 5.54, 5.2, 5.12, 14.42, 14.56, 12.78, 13.11, 18.78, 18.71, 19.19, 11.58, 11.08, 7.89, 17.51, 17.34, 12.55, 12.65, 6.42, 8.49)
df = data.frame(c13,n15,s34)
#create a list to store your results
lst <- list()
#this statement does the repetition (looping)
for(i in 1:1000)
{
mysample <- matrix(sample(c13, 18), ncol=2)
#mysample is a vector
is.atomic(mysample)
#Convert vector to a dataframe for correlation test.
mysample <- as.data.frame(mysample)
is.atomic(mysample)
#name columns
colnames(mysample) <- c ("siblingcarbon1", "siblingcarbon2")
#Conduct a Spearman rank correlation test on these randomly selected values
x <- cor.test(mysample$siblingcarbon1,mysample$siblingcarbon2, method="spearman")
print(x$estimate)
lst[i] <- x$estimate
}
str(lst)
结果将存储在lst中运行的顺序中。跑了10次(而不是1000次):
STR(LST)
List of 10
$ : num -0.5
$ : num -0.1
$ : num 0.15
$ : num -0.8
$ : num 0.0167
$ : num -0.617
$ : num 0.183
$ : num -0.617
$ : num 0.2
$ : num 0.05