Guest User

Untitled

a guest
Jan 15th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. set.seed(1)
  2.  
  3. df1 <- data.frame(id = sample(LETTERS,50,replace=T), val = rnorm(50), val1 = rnorm(50), stringsAsFactors = F)
  4. df2 <- data.frame(id = sample(LETTERS,30,replace=T), val = rnorm(30), val2 = rnorm(30), stringsAsFactors = F)
  5.  
  6. df.list <- list(df1,df2)
  7.  
  8. library(dplyr)
  9. df <- df.list %>% purrr::reduce(dplyr::inner_join,by="id")
  10.  
  11. id val.x val1 val.y val2
  12. 1 G -0.05612874 0.2914462 2.087167 0.7876396
  13. 2 G -0.05612874 0.2914462 -0.255027 1.4411577
  14. 3 J -0.15579551 -0.4432919 -1.286301 1.0273924
  15.  
  16. df.list.colnames <- unlist(lapply(df.list,function(l) colnames(l %>% dplyr::select(-id))))
  17. df.list.colnames <- table(df.list.colnames)
  18. repeating.colnames <- names(df.list.colnames)[which(df.list.colnames > 1)]
  19.  
  20. repeating.colnames.df <- do.call(rbind,lapply(df.list,function(r) r %>% dplyr::select_(.dots = c("id",repeating.colnames)))) %>%
  21. unique()
  22.  
  23. for(r in 1:length(df.list)) df.list[[r]] <- df.list[[r]] %>% dplyr::select_(.dots = paste0("-",repeating.colnames))
  24. df <- df.list %>% purrr::reduce(dplyr::inner_join,by="id")
Add Comment
Please, Sign In to add comment