【发布时间】:2021-03-09 13:13:56
【问题描述】:
我使用动态变量(例如ID)作为引用列名的方式,该列名将根据我当时正在处理的基因而改变。然后我在mutate 中使用case_when 创建一个新列,该列的值取决于动态列。
我认为!! (bang-bang) 是我强制评估变量内容所需要的;但是,我没有在我的新专栏中得到预期的输出。只有!!as.name 给了我期望的输出,我不完全明白为什么。有人可以解释为什么在这种情况下只使用 !! 是不合适的,!!as.name 发生了什么?
这是我制作的一个简单的可重现示例,用于演示我的体验:
library(tidyverse)
ID <- "birth_year"
# Correct output
test <- starwars %>%
mutate(FootballLeague = case_when(
!!as.name(ID) < 10 ~ "U10",
!!as.name(ID) >= 10 & !!as.name(ID) < 50 ~ "U50",
!!as.name(ID) >= 50 & !!as.name(ID) < 100 ~ "U100",
!!as.name(ID) >= 100 ~ "Senior",
TRUE ~ "Others"
))
# Incorrect output
test2 <- starwars %>%
mutate(FootballLeague = case_when(
!!(ID) < 10 ~ "U10",
!!(ID) >= 10 & !!(ID) < 50 ~ "U50",
!!(ID) >= 50 & !!(ID) < 100 ~ "U100",
!!(ID) >= 100 ~ "Senior",
TRUE ~ "Others"
))
# Incorrect output
test3 <- starwars %>%
mutate(FootballLeague = case_when(
as.name(ID) < 10 ~ "U10",
as.name(ID) >= 10 & as.name(ID) < 50 ~ "U50",
as.name(ID) >= 50 & as.name(ID) < 100 ~ "U100",
as.name(ID) >= 100 ~ "Senior",
TRUE ~ "Others"
))
identical(test, test2)
# FALSE
identical(test2, test3)
# TRUE
sessionInfo()
#R version 4.0.2 (2020-06-22)
#Platform: x86_64-centos7-linux-gnu (64-bit)
#Running under: CentOS Linux 7 (Core)
# tidyverse_1.3.0
# dplyr_1.0.2
干杯!
【问题讨论】:
-
仅供参考 rlang 与 as.name 非常接近,称为 sym。在这里使用它会更惯用,并且可以节省一些击键。
标签: r dplyr tidyverse tidyeval nse