Search code examples
rrandomstatistics-bootstrap

R: How to randomly sample one value from each column and bootstrap


I have 18 columns and 100 rows, where columns stand for 18 students and rows stand for their grades in 100 exams. Here is what I want: for each student, I want to randomly sample/select only one grade from all 100 grades. In other words, I want a sample with 18 columns and just 1 row. I have tried apply, sample functions, but all of these just don't work, and I don't know why.

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))

Solution

  • Try this

    apply(data, 2, sample, size = 1)
    

    Use @StupidWolf's data for test:

    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