R 如果列名包含字符串,则更改变量

R 如果列名包含字符串,则更改变量,r,dplyr,R,Dplyr,我的数据有几个列,其中包含字符串“trait”。我想使用dplyr以同样的方式对这些列进行变异 我的第一反应是以以下方式使用mutate_if: my_data %>% mutate_if(contains('trait'), funs(if_else(.=='True',T,F)) ) 但是我得到了错误 Error: Variable context not set 这个错误是什么意思?如何正确使用mutate\u if功能 这是我的一个数据示例(其他一些列也在这里) 您应该将con

我的数据有几个列,其中包含字符串“trait”。我想使用dplyr以同样的方式对这些列进行变异

我的第一反应是以以下方式使用
mutate_if

my_data %>% mutate_if(contains('trait'), funs(if_else(.=='True',T,F)) )
但是我得到了错误

Error: Variable context not set
这个错误是什么意思?如何正确使用
mutate\u if
功能

这是我的一个数据示例(其他一些列也在这里)


您应该将contains(“trait”)变量过滤器包装到vars()调用中


另外,我建议你也不要打
if_else()
电话,直接使用逻辑比较法,这也可能是一种灵活的选择,取决于你的目标

df %>% 
  gather(trait, true_or_false, -name) %>% 
  mutate(true_or_false = case_when(
    str_detect(trait, "argues|avoids") ~ "boo",
    TRUE ~ .$true_or_false
  ))

你能给我解释一下varis()在这里有什么帮助吗?直觉。为避免dplyr 0.8.0警告中不推荐使用
funs()
,请在(vars(contains('trait'),~.='True')处使用波浪号(~)a la:my\u data%>%mutate\u
my_data %>% 
  mutate_at(vars(contains('trait')), funs(.=='True'))
df %>% 
  gather(trait, true_or_false, -name) %>% 
  mutate(true_or_false = case_when(
    str_detect(trait, "argues|avoids") ~ "boo",
    TRUE ~ .$true_or_false
  ))