Advertisement
Guest User

SavingFiles

a guest
Jul 14th, 2019
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.48 KB | None | 0 0
  1. participant <- 1:30
  2. tasks <- c('a','b','c')
  3. session <- 1:20
  4.  
  5. # Make sure our folder exists for saving into.
  6. baseDir <- './AllTheFiles/'
  7. if (!dir.exists(baseDir)) {dir.create(baseDir)}
  8.  
  9. # Here is a pretty traditional computer-languagy way to do it:
  10. for (p in participant) {
  11.   for (tsk in tasks) {
  12.     for (s in session) {
  13.       # This step just generates random data to write.
  14.       currentDf <- data.frame(
  15.         rndNum1 = rnorm(10),
  16.         rndNum2 = runif(10)
  17.       )
  18.      
  19.       # Construct a different file name for each case.
  20.       flNm <- paste(p, tsk, s, sep = "_")
  21.       # Write the file. Note the paste0() statement, which ensures that the
  22.       # files end up in a folder called "AllTheFiles" (in the current working
  23.       # directory). It also adds the txt file extension.
  24.       write.table(
  25.         currentDf,
  26.         file = paste0(baseDir, flNm, ".txt")
  27.       )
  28.     }
  29.   }
  30. }
  31.  
  32. # A slightly more R-y way to do it
  33. combos <- expand.grid(participant, tasks, session, stringsAsFactors = F)
  34.  
  35. apply(combos, MARGIN = 1, function (combo) {
  36.     # This code is the same as in the for-loop way, but referencing the combos
  37.     # object instead of looping directly on the original objects.
  38.     p <- combo[1]
  39.     tsk <- combo[2]
  40.     s <- combo[3]
  41.    
  42.     currentDf <- data.frame(
  43.       rndNum1 = rnorm(10),
  44.       rndNum2 = runif(10)
  45.     )
  46.     flNm <- paste(p, tsk, s, sep = "_")
  47.     write.table(
  48.       currentDf,
  49.       file = paste0(baseDir, flNm, ".txt")
  50.     )
  51.   }
  52. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement