Home > database >  R - filtering and merging multiple objects
R - filtering and merging multiple objects

Time:09-23

Can anyone tell me an elegant solution to achieve the same result with less code? As far as I know, there is no "un-filter" in R.

test1 <- dat_long%>%
  filter(time == "0month") %>%
  merge(blood_m1,  by="ID")  


test2 <- dat_long%>%
  filter(time == "3month") %>%
  merge(blood_m2,  by="ID")   

test3 <- dat_long%>%
  filter(time == "4month") %>%
  merge(blood_m3,  by="ID") 



test_long <- test3  %>%
  bind_rows(test2 )%>%
  bind_rows(test1 )

Basically, I want to achieve the "test_long" df by generating a single object and all connect with %>%. Thanks!

CodePudding user response:

I think you want a cleaner blood_all lookup table to begin with, here's a suggestion :

library(dplyr)

blood_all <- 
  # create named list
  list("0month" = blood_m1, "3month" = blood_m2, "4month", blood_m3) %>% 
  # bind into a single tibble, placing names into "time" column
  bind_rows(, .id = "time")

test <- dat_long %>%
  merge(blood,  by=c("ID", "time"))  # or inner_join to keep it tidyverse
  • Related