Hagen Brenner Hagen Brenner - 2 months ago 10
R Question

How to convert a string in a function into an object?

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

Answer

The trick is to use parse. For instance:

> x <- "A"
> eval(parse(text=paste("df$", x, sep = "")))
 [1]  1  2  3  4  5  6  7  8  9 10

See also this Q/A: R eval expression

Comments