r - 从 mutate 中的符号创建列(整洁的评估)
问题描述
所以我想创建一个名为var
所有行的文本“测试”的新列。即结果应该是这样的mtcars$var <- "testing"
。我尝试过不同的东西,例如as_name
,as_string
...
library(tidyverse)
f <- function(df, hello = testing){
df %>%
mutate(var = hello)
}
f(mtcars)
解决方案
我们可以做的:
f <- function(df, hello = testing){
hello <- deparse(substitute(hello))
df %>%
mutate(var =rlang::as_name(hello))
}
f(mtcars)
但是,正如@Lionel Henry 所指出的(请参阅下面的评论):
deparse
不会检查简单的输入,可能会返回一个字符向量。然后 as_name() 如果长度 > 1 向量将失败,否则什么也不做,因为它已经是一个字符串as_name(substitute(hello)) 做同样的事情,但检查输入是一个简单的符号或字符串。它比 as_label() 更受约束
因此,最好将其重写为:
f <- function(df, hello = testing){
hello <- as_label(substitute(hello))
df %>%
mutate(var = hello )
}
或者:
f <- function(df, hello = testing){
hello <- rlang::as_name(substitute(hello))
df %>%
mutate(var = hello)
}
结果:
mpg cyl disp hp drat wt qsec vs am gear carb var
1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 testing
2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 testing
3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 testing
推荐阅读
- android - 如何删除撰写视图上的阴影?
- twitter - 如何防止 Twitter API 中状态更新的自动链接预览生成?
- javascript - 使用循环更改背景颜色
- javascript - UnhandledPromiseRejectionWarning:MongoError:无法使用已结束的会话
- javascript - 如果条件为真或假,我们可以在组件内传递三元表达式并作为道具发送吗
- html - 无法部分返回从标题生成的图像 - Hugo
- html - 1 多个播放器的音量控制器?
- raspberry-pi - bluetoothctl 不显示蓝牙低功耗 (BLE) 设备
- bash - bash 导出未包含在 kubectl 命令中
- python - Flask Python 如何将输入从文本框传递到 POST 请求?