SteveS
SteveS

Reputation: 4040

dplyr select one_of() helper returns a warning?

I have two major dataframes with 2 sets of column names I want to drop:

df1 <- structure(list(a = c(1, 2), b = c(3, 4), c = c(5, 6), d = c(7, 
8), e = c(9, 10)), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))

df2 <- structure(list(a = c(1, 2), b = c(3, 4), c = c(5, 6)), row.names = c(NA, 
-2L), class = c("tbl_df", "tbl", "data.frame"))

I want to drop any column names in the following list: "c", "d", "e".

When I just do it with one_of() select helper I get a warning:

> tibble(a = c(1,2), b = c(3,4), c = c(5,6)) %>% select(-one_of("c","d","e"))
# A tibble: 2 x 2
      a     b
  <dbl> <dbl>
1     1     3
2     2     4
Warning message:
Unknown columns: `d`, `e` 

and 0 warning for the bigger one.

Please advise how can I filter by bank of column names without warnings? If a column I want to ignore exists in the one_of() ignore it, otherwise keep it.

Upvotes: 2

Views: 1476

Answers (2)

Rajkumar ManiRaja
Rajkumar ManiRaja

Reputation: 110

I hope my answer will solve your problem, I used select_if function instead of using select's helper function. If you want to know more about select_if type ?select_if in RStudio console

tibble(a = c(1,2), b = c(3,4), c = c(5,6)) %>% select_if(colnames(.) %in% c("a","c","d","e"))

Thanks!

Upvotes: 4

smau
smau

Reputation: 11

You can use

options(warn=-1)

This will turn off warning messages globally to turn it on back you can run command like:

options(warn=0) 

This is not recommended, just work around for your requirement.

To Supress warning only for this code you can use Trycatch():

tryCatch(
suppressWarnings( tibble(a = c(1,2), b = c(3,4), c = c(5,6)) %>%
select(-one_of("c","d","e"))  
  )
  );

Upvotes: 1

Related Questions