我想将我在函数中传递的字符串转换为对象(或列名).
我知道这有效:
df <- data.frame(A = 1:10, B = 11:20)
test.function <- function(x)
{
z <- df[[x]]
return(z)
}
test.function("A")
Run Code Online (Sandbox Code Playgroud)
我不想使用[[.]]运算符,因为有时它不实用甚至不适用.我在一个将字符串转换为"对象"的通用方法中得到了强调.因此我尝试了以下方法:
df <- data.frame(A = 1:10, B = 11:20)
test.function <- function(x)
{
z <- get(paste("df$", x, sep = ""))
return(z)
}
test.function("A")
Run Code Online (Sandbox Code Playgroud)
要么
df <- data.frame(A = 1:10, B = 11:20)
test.function <- function(x)
{
z <- as.name(paste("df$", x, sep = ""))
return(z)
}
test.function("A")
Run Code Online (Sandbox Code Playgroud)
要么
df <- data.frame(A = 1:10, B = 11:20)
test.function <- function(x)
{
z <- df$as.name(x)
return(z)
}
test.function("A")
Run Code Online (Sandbox Code Playgroud)
我还尝试使用parse,do.call和eval函数.不幸的是,我失败了
Joh*_*lby 26
诀窍是使用parse.例如:
> x <- "A"
> eval(parse(text=paste("df$", x, sep = "")))
[1] 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)
另请参见此问答:评估以字符串形式给出的表达式
我刚刚得到一个upvote,它在5年之后把我带回了这个问题.我仍然认为正确的答案是[[尽管OP要求不使用它,但这里有一种打扮[[成更实用的"功能"的方法.
df <- structure(list(x = 1:3, y = 1:3), .Names = c("x", "y"), row.names = c(NA,
-3L), class = "data.frame")
test.function <- `[[` # So simple, `test.function` now has all the features desired.
df
x y
1 1
2 2
3 3
test.function(df, "x")
#[1] 1 2 3
Run Code Online (Sandbox Code Playgroud)
或者,如果需要硬编码从调用环境中提取一个名为"df"的对象,那么这个命题似乎具有可疑的安全性:
test.df_txt <- function(var, dfn ='df' ){ get(dfn)[[var]] }
test.df_txt("x")
#[1] 1 2 3
Run Code Online (Sandbox Code Playgroud)
原始回复(仍然不推荐):
如果你愿意使用eval(parse(text = ...)),你可以绕过"$"的限制:
test.function <- function(x) {
z <- eval(parse( text=paste("df$", x, sep = "")), env=.GlobalEnv)
return(z)
}
test.function("A")
# [1] 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)
但是......使用"[["更好.(我最初的努力eval(parse()是因为不太了解使用"文本"参数parse.)
In addition to eval(parse(text=YOUR_STRING)), you can use as.symbol as a potential alternative.