我有18列和100行,其中列代表18个学生,行代表其100次考试的成绩。这就是我想要的:对于每个学生,我想从所有100个成绩中随机抽样/选择一个成绩。换句话说,我想要一个18列,只有1行的样本。我已经尝试过应用示例函数,但是所有这些都不起作用,我也不知道为什么。任何帮助将不胜感激!非常感谢!
bs = data.frame(matrix(nrow=1,ncol=18))
for (i in colnames(high)){
bs[,i]=sample(high[,i],1,replace=TRUE)
}
as.data.frame(lapply(high[,i],sample,18,replace=TRUE))
假设您的数据是这样的:
set.seed(100)
high = matrix(runif(100*18),ncol=18)
colnames(high) = paste0("student",1:18)
rownames(high) = paste0("exam",1:100)
head(high)
student1 student2 student3 student4 student5 student6 student7
exam1 0.30776611 0.32741508 0.3695961 0.8495923 0.5112374 0.2202326 0.03176634
exam2 0.25767250 0.38947869 0.9563228 0.6532260 0.2777107 0.7431595 0.57970549
exam3 0.55232243 0.04105275 0.9135767 0.9508858 0.3606569 0.3059573 0.15420484
exam4 0.05638315 0.36139663 0.8233363 0.6172230 0.4375279 0.4022088 0.12527050
您想要做的是将样品1到100,进行18次更换(类似于自举程序,这要感谢@ H1指出):
set.seed(101)
take=sample(1:100,18,replace=TRUE)
take
[1] 73 57 46 95 81 58 95 61 60 59 99 3 32 9 96 99 99 98
从上面可以看到,replace=TRUE
拍摄了99次。我们将在第1列输入73,在第2列输入56,依此类推。这可以通过以下方式完成:
high[cbind(take,1:18)]
[1] 0.57256477 0.84338121 0.71225050 0.56432392 0.23865929 0.23563641
[7] 0.51903694 0.36692427 0.51577410 0.45780908 0.19434773 0.70247028
[13] 0.60383059 0.25451088 0.78583242 0.86241707 0.05360842 0.61892604
尝试一下
apply(data, 2, sample, size = 1)
使用@StupidWolf的数据进行测试:
set.seed(101)
apply(high, 2, sample, size = 1)
# student1 student2 student3 student4 student5 student6 student7 student8 student9 student10 student11 student12 student13 student14 student15 student16 student17 student18
# 0.57256477 0.84338121 0.71225050 0.56432392 0.23865929 0.23563641 0.51903694 0.36692427 0.51577410 0.45780908 0.19434773 0.70247028 0.60383059 0.25451088 0.78583242 0.86241707 0.05360842 0.61892604
您可以使用sample()
随机选择一列。
我在这里创建了一个小的数据样本。如果您提供样本数据以最好地理解问题,将很有帮助。
# sample data
df <- data.frame(
student1 = c(50, 45, 86, 30),
student2 = c(56, 78, 63, 58),
student3 = c(88, 60, 75, 93),
student4 = c(87, 33, 49, 11),
student5 = c(85, 96, 55, 64)
)
然后,您遍历每条考试记录,并随机选择一个学生的成绩并将其存储在矢量中。最后,由于需要数据帧,因此可以将向量转换为数据帧。
# column names
students <- colnames(df)
# empty vector
vals <- c()
for(s in students) {
grade <- sample(df[[s]], 1)
vals <- c(vals, grade)
}
finalDF <- as.data.frame(t(vals))
names(finalDF) <- students
finalDF
我运行的2次迭代的输出是-
student1 student2 student3 student4 student5
1 45 78 93 87 64
student1 student2 student3 student4 student5
1 45 63 93 87 96
其他答案确实很聪明,但是我希望这会有所帮助!