Subset tibble columns based on values in another tibble

Viewed 356

I've searched the best that I could, but am still struggling with my problem. I am trying to subset columns in a tibble based on the values from another tibble.

More specifically, I have a tibble of socio-economic indicators:

cname   year  ccodealp  wdi_lfpr wdi_lfprf

Turkey  2010    TUR    51.611    29.592 
Turkey  2011    TUR    52.781    30.995 
Turkey  2012    TUR    52.809    31.676 
Turkey  2013    TUR    53.874    33.125 
Turkey  2014    TUR    54.597    33.446 
Turkey  2015    TUR    55.594    34.858 

I have a separate tibble (Tibble 2) with two columns, the indicator and the % missingness of that indicator within Tibble 1

tibble_2
col         value
who_dwtot   100         
who_dwrur   100         
who_dwurb   100

What I want to do is subset tibble_1 to only have columns that meet a certain criteria in tibble_2. Namely, only retain columns that have less than 90% missingness (the "value" column in tibble_2). I'm having trouble going about this in tidyverse. This the code I've tried:

tibble_1 %>% select(tibble_2, "value" < 90)

Error: Must subset columns with a valid subscript vector. 
x Subscript has the wrong type `tbl_df< col : character value: double >`. i 
It must be numeric or character. Run `rlang::last_error()` to see where the error occurred.

I know this is probably a trivial problem, but I'm not an expert in tidyverse and can't figure out how to fix this.

Thanks for any help.

1 Answers

We can filter the 'tibble_2' based on the 'value' column and pull the 'col' for selecting the column names in tibble_1

library(dplyr)
tibble_1 %>%
     select({tibble_2 %>%
                 filter(value < 90) %>%
                 pull(col)})

Or if we use base R

subset(tibble_1, select = subset(tibble_2, value < 90, select = col)$col)
Related