我花了很多时间在这上面,希望有人能提供建议。我有一段使用 funs() 的代码,该代码已被软弃用,因此尝试了替代方案,但无法使其按预期工作。
旧:
df %>% mutate_at(vars(x,y,z),
.funs = funs(Comment = case_when(
.%in% "YES") ~ deparse(substitute(.))))
这给出了三个新变量:x_Comment、y_Comment 和 z_Comment - 如果相关变量包含“YES”,则将包含相关变量名称(“x”、“y”或“z”)
更新:
df %>% mutate_at(vars(x,y,z),
.funs = list(Comment = ~case_when(
.%in% "YES") ~ deparse(substitute(.))))
我已经根据有关 funs() 被软弃用的警告更新了代码,但是上面的方法不起作用。它按预期给出了三个新变量:x_Comment、y_Comment 和 z_Comment - 但是,如果相关变量包含“YES”,则会给出“.”。而不是变量名。
任何解决方案 - 最好是 tidyverse 非常感谢!
谢谢!
最佳答案
这符合你的要求吗?
library(tidyverse)
df <- tibble(
x=c("Yes", "No", "No"),
y=c("No", "Yes", "No"),
z=c("No", "No", "Yes")
)
df %>%
mutate(
across(everything(),
~ifelse(.x == "Yes", cur_column(), ""),
.names="Comment_{col}")
)
# A tibble: 3 x 6
x y z Comment_x Comment_y Comment_z
<chr> <chr> <chr> <chr> <chr> <chr>
1 Yes No No "x" "" ""
2 No Yes No "" "y" ""
3 No No Yes "" "" "z"
请注意,mutate_at
也已弃用。
关于r - dplyr::funs() 软弃用 - 更新以返回变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65072853/