Home > front end >  R Loop to store repeated results of t.tests in data frame
R Loop to store repeated results of t.tests in data frame

Time:03-29

I have no loop experience and need a loop to:

  • downsample a data frame
  • do a t test and store the results
  • extract the confidence limits
  • add confidence limits to a data frame
  • and redo say 100 times and append each iteration to the list. Below is the code for one iteration. I would like a data frame with 100 rows and 2 columns i.e. the upper and lower limits
df  = c(3,5,4,3,2,6,7,5,4,2,3,4,5,7,8,4,3,2,6,8,9,7,6,5,4,2,3,4,3,2,3,4,56,7,87) # dummy data
df2 = (sample(df, 20)) # take 20 samples of df data
tt  = t.test(df2) # perform t test and store results
cl = tt$conf.int # extract only the upper and lower confidence limits and store
cl_list = data.frame(cl) # make into a dataframe 
cl_list = t(cl_list) # transpose dataframe so that col_1 is the Lower UCL and col_2 is the Upper

CodePudding user response:

You can use lapply(), and then use do.call(rbind,...) to a matrix, set to data.frame, and rename columns:

setNames(data.frame(do.call(rbind,
  lapply(1:100, function(x) {
    t(t.test(sample(df,20))$conf.int)
  })
)),c("lower", "upper"))

Output: (first six rows of 100)

      lower    upper
1 1.7378652 21.56213
2 0.4650324 17.73497
3 0.5198734 17.78013
4 1.9602563 12.83974
5 1.3473073 12.35269
6 0.2490264 17.55097

You could also use replicate

setNames(data.frame(
  t(replicate(t.test(sample(df,20))$conf.int,n=100))
), c("lower", "upper"))

Output (again, first six rows, of 100, different output, no seed set)

      lower     upper
1 0.5774575 17.822543
2 3.5952854  5.404715
3 3.7792077  5.720792
4 1.7471739 21.552826
5 0.9553992 20.944601
6 2.4087922 13.191208

You can also use a traditional for loop, like this:

result = matrix(NA,nrow = 100,ncol = 2)
for(i in 1:100) {
  result[i,] <- t(t.test(sample(df,20))$conf.int)
}
setNames(data.frame(result), c("lower", "upper"))

Output:

        lower    upper
1  2.23601345 13.06399
2 -0.07824891 17.27825
3  0.12547144 17.47453
4  1.96874001 12.83126
5  0.19719426 17.50281
6  3.34230034  4.85770
  • Related