I would like to convert a string that I pass in a function into an object (or column name).
I know that this works:
df <- data.frame(A = 1:10, B = 11:20)
test.function <- function(x)
{
z <- df[[x]]
return(z)
}
test.function("A")
I don't want to use the [[.]] operator, because sometimes it is unpractical or even not applicable. I am interessted in a general method to convert a string into an "object". Therefore I tried the following:
df <- data.frame(A = 1:10, B = 11:20)
test.function <- function(x)
{
z <- get(paste("df$", x, sep = ""))
return(z)
}
test.function("A")
or
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")
or
df <- data.frame(A = 1:10, B = 11:20)
test.function <- function(x)
{
z <- df$as.name(x)
return(z)
}
test.function("A")
I also tried to play around with the parse, do.call and eval functions. Unfortunatelly I failed
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…