【问题标题】:Is there a way to create a function to be used inside mutate isnside %>%有没有一种方法可以创建一个在 %>% 内的 mutate 中使用的函数
【发布时间】:2022-11-22 23:18:31
【问题描述】:

这就是我想要实现的。创建一个我可以重复使用许多变量的函数。

library(dplyr)

set.seed(2022)
mydata <- tibble::tibble(
  "id" = 1:100,
  "a1" = sample(c(rep("Yes", 40), rep_len(NA, 100)), 100),
  "a2" = sample(c(rep("Yes", 50), rep_len(NA, 100)), 100),
  "a3" = sample(c(rep("Yes", 40), rep_len(NA, 100)), 100),
  "a4" = sample(c(rep("Yes", 50), rep_len(NA, 100)), 100),
  "b2" = rnorm(100, 50, 10)
)

#  Goal is to capture any occurrence of non missing for (a* variables)


avars <- paste0("a", 1:4)

mydata %>%
  mutate(afin = ifelse(rowSums(!is.na(select(., all_of(avars))))>1, "Yes", "No")) %>%
  count(afin)

# Function (Does not work)

anymatch <- function(vars){
  ifelse(rowSums(!is.na(select(., all_of(vars))))>=1, "Yes", "No")
}


mydata %>%
  mutate(afin = anymatch(avars))

【问题讨论】:

  • 简短的回答是的,这是可能的。在这里查看更多信息:dplyr.tidyverse.org/articles/programming.html
  • 在 Flickinger 先生的回答中,您还可以将 vars 包裹在花括号中,如 {{vars}} 代替 all_of

标签: r dplyr


【解决方案1】:

如果您总是要在 mutate 中的 dplyr 更改中使用此函数,那么您可以使用 cur_data() 获取当前 data.frame 而不是 .。实际上,即使不使用函数,始终使用 cur_data() 而不是 . 可能更安全

anymatch <- function(vars){
  ifelse(rowSums(!is.na(select(cur_data(), all_of(vars))))>=1, "Yes", "No")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-08
    • 2010-09-06
    • 2011-02-16
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 2014-03-25
    • 2019-09-15
    相关资源
    最近更新 更多