如无现有栏目,则以下职能在数据框架中的第一个现有栏目即
library(dplyr, warn.conflicts = FALSE)
#> Warning: package dplyr was built under R version 4.2.3
# `dplyr::coalesce` return fist non-missing, but these columns must exist
return_exist_var <- function(.var1, .var2, .fill = NA, .data) {
# get the . from magrittr::%>%
.data <- get(".", parent.frame())
stopifnot(is.data.frame(.data))
.var1 <- rlang::enexpr(.var1)
.var2 <- rlang::enexpr(.var2)
if (rlang::as_string(.var1) %in% names(.data)) {
return(rlang::parse_expr(rlang::as_string(.var1)))
} else if (rlang::as_string(.var2) %in% names(.data)) {
return(rlang::parse_expr(rlang::as_string(.var2)))
} else {
return(.fill)
}
}
df <- data.frame(
ID = c("ID01", "ID01", "ID02", "ID02"),
v1 = c("a", "b", "c", NA),
v2 = c("A", "B", "C", "C")
)
return first existing column
df %>% dplyr::mutate(NEW = !!return_exist_var(v1))
#> ID v1 v2 NEW
#> 1 ID01 a A a
#> 2 ID01 b B b
#> 3 ID02 c C c
#> 4 ID02 <NA> C <NA>
return first existing column in two column
df %>% dplyr::mutate(NEW = !!return_exist_var(v2, v1))
#> ID v1 v2 NEW
#> 1 ID01 a A A
#> 2 ID01 b B B
#> 3 ID02 c C C
#> 4 ID02 <NA> C C
return second existing column in two column
df %>% dplyr::mutate(NEW = !!return_exist_var(v1_x, v2))
#> ID v1 v2 NEW
#> 1 ID01 a A A
#> 2 ID01 b B B
#> 3 ID02 c C C
#> 4 ID02 <NA> C C
return NA if two column not eixst
df %>% dplyr::mutate(NEW = !!return_exist_var(v1_X, v2_X))
#> ID v1 v2 NEW
#> 1 ID01 a A NA
#> 2 ID01 b B NA
#> 3 ID02 c C NA
#> 4 ID02 <NA> C NA
work well on grouped data frame
df %>%
dplyr::group_by(ID) %>%
dplyr::mutate(NEW = !!return_exist_var(v1))
#> # A tibble: 4 × 4
#> # Groups: ID [2]
#> ID v1 v2 NEW
#> <chr> <chr> <chr> <chr>
#> 1 ID01 a A a
#> 2 ID01 b B b
#> 3 ID02 c C c
#> 4 ID02 <NA> C <NA>
Problem
如何更新职能,然后将职能称为“无<条码>!
df %>% dplyr:mutate(NEW=回报_exist_var(v1)