gpt4 book ai didi

r - 在选择函数中将不带引号的参数作为字符传递

转载 作者:行者123 更新时间:2023-12-03 08:52:46 25 4
gpt4 key购买 nike

我有一个数据框:

data <- data.frame(
name = c("John", "Paul", "George", "Ringo", "Stuart", "Pete"),
instrument1 = c("guitar", "bass", "guitar", "drums", "bass","drums"),
instrument2 = c("guitar", "bass", "guitar", "drums", "bass","drums"),stringsAsFactors=FALSE)

我创建了一个这样的函数:

sel <- function(df, variable) {
var <- enquo(variable)
df2 <- select(df, starts_with(!!var))
return(df2)
}

如何使用此命令运行此功能:

sel(data, instrument)

无需引用参数“instrument”。我需要它不被引用,因为这是一个更大的函数的一部分。如果我像上面那样运行它,我会得到:

Error in is_string(match) : object 'instrument' not found 

最佳答案

您正在寻找deparse(substitute(x))魔法!它将返回您以字符串形式传入的参数名称。

data <- data.frame(
name = c("John", "Paul", "George", "Ringo", "Stuart", "Pete"),
instrument1 = c("guitar", "bass", "guitar", "drums", "bass","drums"),
instrument2 = c("guitar", "bass", "guitar", "drums", "bass","drums"),stringsAsFactors=FALSE)

sel <- function(df, variable) {
var <- deparse(substitute(variable))
df2 <- select(df, starts_with(!!var))
return(df2)
}

sel(data, instrument)

返回结果:

  instrument1 instrument2
1 guitar guitar
2 bass bass
3 guitar guitar
4 drums drums
5 bass bass
6 drums drums

关于r - 在选择函数中将不带引号的参数作为字符传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57899990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com