【发布时间】:2011-11-19 18:07:22
【问题描述】:
我想将我在函数中传递的字符串转换为对象(或列名)。
我知道这行得通:
df <- data.frame(A = 1:10, B = 11:20)
test.function <- function(x)
{
z <- df[[x]]
return(z)
}
test.function("A")
我不想使用 [[.]] 运算符,因为有时它不切实际甚至不适用。我对将字符串转换为“对象”的通用方法感兴趣。因此我尝试了以下方法:
df <- data.frame(A = 1:10, B = 11:20)
test.function <- function(x)
{
z <- get(paste("df$", x, sep = ""))
return(z)
}
test.function("A")
或
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")
或
df <- data.frame(A = 1:10, B = 11:20)
test.function <- function(x)
{
z <- df$as.name(x)
return(z)
}
test.function("A")
我还尝试使用 parse、do.call 和 eval 函数。可惜我失败了
【问题讨论】:
标签: r