Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. #Libraries
  2. library("reshape")
  3. library("data.table")
  4.  
  5. #Specify list of multiple dataframes
  6. filelist <- list(data.frame(x=c(1,1,1,2,2,2,3,3,3), y=c(1,2,3,1,2,3,1,2,3), a=1:9),
  7. data.frame(x=c(1,1,1,2,2,2,3,3,4), y=c(1,2,3,1,2,3,1,2,1), b=seq(from=0, by=5, length.out=9)),
  8. data.frame(x=c(1,1,1,2,2,2,3,3,4), y=c(1,2,3,1,2,3,1,2,2), c=seq(from=0, by=10, length.out=9)))
  9.  
  10. #Merge with merge_recurse()
  11. listMerged <- merge_recurse(filelist, by=c("x","y"))
  12.  
  13. #Attempt with data.table
  14. ids <- lapply(filelist, function(x) x[,c("x","y")])
  15. unique_keys <- unique(do.call("rbind", ids))
  16. dt <- data.table(filelist)
  17. setkey(dt, c("x","y")) #error here
  18.  
  19. Reduce(function(x, y) x[y[J(unique_keys)]], filelist)
  20.  
  21. > listMerged
  22. x y a b c
  23. 1 1 1 1 0 0
  24. 2 1 2 2 5 10
  25. 3 1 3 3 10 20
  26. 4 2 1 4 15 30
  27. 5 2 2 5 20 40
  28. 6 2 3 6 25 50
  29. 7 3 1 7 30 60
  30. 8 3 2 8 35 70
  31. 9 3 3 9 NA NA
  32. 10 4 1 NA 40 NA
  33. 11 4 2 NA NA 80
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement