[英]opposite of mutate_at in dplyr
I need the opposite of mutate_at in dplyr. 我需要在dplyr中与mutate_at相反。 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. 结果是将var_to_be_modified更改为dbl。
Turning @Axeman's comment into an answer as community wiki: 将@ Axeman的评论转变为社区维基的答案:
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
: 从
vars
的帮助页面:
Arguments
参数
... Variables to include/exclude in mutate/summarise.
...变量/摘要中包含/排除的变量。 You can use same specifications as in select().
您可以使用与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 如果我们传递一个字符向量,请使用
one_of
这是删除列的规范方法
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
根据
?select_helpers
one_of(): Matches variable names in a character vector.
one_of():匹配字符向量中的变量名称。
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
is_character(x)出错:找不到对象'hello'
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 换句话说,如果OP希望整个管道最终出错,第二个选项更好,如果它仍然有效,但有警告,可以使用这篇文章中的选项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.