r - dplyr::funs() 软弃用 - 更新以返回变量名称

标签 r dplyr tidyverse deprecated

我花了很多时间在这上面,希望有人能提供建议。我有一段使用 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/

相关文章:

r - dplyr:函数错误消息

r - 我可以告诉 dplyr 的 select() 获取索引行吗?

r - grouped_df_impl(data, unname(vars), drop) : 中的错误

在调用 mutate() 时引用上一列/下一列

r - 在 R 中,向量和数据帧是有序集还是无序集?

r - 转换列表输出以在 dplyr 管道中创建 data.frame

r - 将错误结果的数字分箱

R将列表转换为成对的连续元素

r - 如何查找跨多个变量列的最大组百分比

r - 具有频率和百分比的双向列联表