Home > Enterprise >  How to filter columns with another file's dummy
How to filter columns with another file's dummy

Time:09-17

I have two data frames that look like this:

df1 <- data.frame(date = c("01.01.", "02.01.", "03.01.", "04.01.", "05.01."),
                  A = c(102, 75, 99, 175, 60),
                  B = c(94, 37, 140, 63, 87),
                  C = c(55, 23, 90, 102, 107))

df2 <- data.frame(ID = c("A", "B", "C"),
                  dummy = c(1, 0, 1))

I'm now trying to create a df3 using the select() function in dplyr. The result should only include those who have a dummy == 1, meaning that df3 would only have column A and C remaining. However, since the dummy is found in a separate file, and can't really be merged into the first one, I am unsure how to do this. Thanks!

CodePudding user response:

Is this what you want?

library(dplyr)
df3 <- df1 %>%
  select(matches(df2 %>% filter(dummy == 1) %>% 
                   pull(ID)))

If you want it without the date column, add ignore.case = FALSE to the matches function, i.e.

df3 <- df1 %>%
  select(matches(df2 %>% filter(dummy == 1) %>% 
                   pull(ID), ignore.case = FALSE))

Output:

   A   C
1 102  55
2  75  23
3  99  90
4 175 102
5  60 107

CodePudding user response:

library(dplyr)
df1 %>% 
  select(df2$ID[df2$dummy == 1])
    A   C
1 102  55
2  75  23
3  99  90
4 175 102
5  60 107

CodePudding user response:

Using base R

 subset(df1, select = df2$ID[as.logical(df2$dummy)])
    A   C
1 102  55
2  75  23
3  99  90
4 175 102
5  60 107
  • Related