Advertisement
Guest User

Untitled

a guest
Sep 27th, 2016
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. # Create a sub-folder into which we create files.
  2. dir.create("temp_dir")
  3. setwd("temp_dir")
  4.  
  5. # Create some files in temp_dir.
  6. sapply(1:10, FUN = function(i) {
  7. xy <- data.frame(a = rnorm(10), b = rnorm(10), c = rnorm(10))
  8. write.table(xy, file = sprintf("filename_%s.txt", i), row.names = FALSE, col.names = TRUE)
  9. })
  10.  
  11. # Find relevant files, you can use pattern to match if folder doesn't contain only
  12. # files in question.
  13. all.files <- list.files(pattern = "filename_")
  14.  
  15. # Read in all files. do not simplify the result because we'll need it "raw". The
  16. # result is a list.
  17. all.dfs <- sapply(all.files, FUN = read.table, header = TRUE, simplify = FALSE)
  18.  
  19. # Calculate grand mean of the data.frame.
  20. all.means <- lapply(all.dfs, FUN = function(x) mean(sapply(x, mean)))
  21.  
  22. # Corce from a list to a vector.
  23. one.mean <- as.numeric(all.means)
  24.  
  25. # Calculate mean for each column.
  26. mean(one.mean)
  27.  
  28. # Clean up this example.
  29. setwd("../")
  30. unlink("temp_dir")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement