假设您有一个数据框,其变量名为X1-X30和Y1-Y30。这些变量中的每一个都保存着1到5的整数。我们希望像这样从X开始重新编码一些变量:
df %<>%
mutate_at(vars(starts_with("X") &
ends_with("5", "8", "16", "22", "28")),
recode, "1" = 5, "2" = 4, "4" = 2, "5" = 1)
但是,这将返回以下错误:
Error in UseMethod("recode") :
no applicable method for 'recode' applied to an object of class "c('tbl_df', 'tbl', 'data.frame')"
这是因为重新编码需要使用向量作为参数。那么,如何绕过这种情况呢?
mutate_at
完全被设计为采用以向量为参数的函数,例如recode
,这不是问题。你的错误是只因为你不使用选择助手与链逻辑调用&
,而不是将它们用链表,
内vars()
。
另外,如果您想要的是目标,则可以使用matches
来选择仅以X开头并以某些数字结尾的列。
library(dplyr)
set.seed(123)
df <- data.frame("X1" = sample(1:5, 10, TRUE),
"X2" = sample(1:5, 10, TRUE),
"X3" = sample(1:5, 10, TRUE))
df
#> X1 X2 X3
#> 1 3 5 2
#> 2 3 3 1
#> 3 2 3 3
#> 4 2 1 4
#> 5 3 4 1
#> 6 5 1 3
#> 7 4 1 5
#> 8 1 5 4
#> 9 2 3 2
#> 10 3 2 5
df %>%
mutate_at(vars(matches("^X.*1|2$")),
recode, "1" = 5, "2" = 4, "3" = 3,"4" = 2, "5" = 1)
#> X1 X2 X3
#> 1 3 1 2
#> 2 3 3 1
#> 3 4 3 3
#> 4 4 5 4
#> 5 3 2 1
#> 6 1 5 3
#> 7 2 5 5
#> 8 5 1 4
#> 9 4 3 2
#> 10 3 4 5
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句