简体   繁体   中英

opposite of mutate_at in dplyr

I need the opposite of mutate_at in dplyr. I want to select a group of columns not specified in the variable list.

df <- tibble(var_not_to_be_modified = sample(c("T","F"),10, replace = TRUE),
             var_to_be_modified     = sample(c(1,0)    ,10, replace = TRUE) )

df %>%
mutate_at(c("var_not_to_be_modified"), as.numeric)

Result would be to change var_to_be_modified to dbl.

Turning @Axeman's comment into an answer as community wiki:

library(dplyr)
df %>%
  mutate_at(., vars(-var_not_to_be_modified), as.numeric)
 # A tibble: 10 x 2
#   var_not_to_be_modified var_to_be_modified
#   <chr>                               <dbl>
# 1 F                                       1
# 2 F                                       1
# 3 F                                       1
# 4 F                                       1
# 5 F                                       1
# 6 T                                       0
# 7 T                                       1
# 8 F                                       1
# 9 F                                       0
#10 T                                       1

From the help page of vars :

Arguments

... Variables to include/exclude in mutate/summarise. You can use same specifications as in select(). If missing, defaults to all non-grouping variables.

If we are passing a character vector, use one_of which is the canonical way to remove columns

library(dplyr)
df %>%
  mutate_at(vars(-one_of(c("var_not_to_be_modified"))), as.numeric)
# A tibble: 10 x 2
#   var_not_to_be_modified var_to_be_modified
#   <chr>                               <dbl>
# 1 F                                       1
# 2 F                                       1
# 3 T                                       1
# 4 F                                       0
# 5 T                                       0
# 6 F                                       1
# 7 T                                       1
# 8 T                                       1
# 9 F                                       0
#10 T                                       1

According to ?select_helpers

one_of(): Matches variable names in a character vector.


If we pass a column name that is not in the data, the behavior is different. Here, it wouldn't end up in an error

 df %>% 
     mutate_at(vars(-one_of("hello")), as.numeric)

and

df %>%
    mutate_at(vars(-hello), as.numeric)

Error in is_character(x) : object 'hello' not found

In other words, if the OP wanted the whole pipeline to end up in an error, the second option is better and if it still works, but with a warning, the option in this post can be used

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM