Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

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

$
0
0

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


Viewing all articles
Browse latest Browse all 201839

Trending Articles