0

I have a dataframe called returns with different columns, for instance simple. I normally access it by returns$simple. Now I need to pass these columns on to a function. I tried many things that I found here on the board (as.formula, parse, paste, etc.) and none of it worked.

test = function(x) 
{ 
  returns$x
}
test(simple)
Thomas
  • 43,637
  • 12
  • 109
  • 140
Felix Dietrich
  • 127
  • 1
  • 11

3 Answers3

1

You could access your columns using the bracket notation. Here's how you do it:

test = function(x) 
{ 
    returns[,x]
}
test("simple")

Or simply (without using a function):

returns[, column_name]
Matt
  • 17,290
  • 7
  • 57
  • 71
0

Try this

returns[,x]                    # a

or get column id, using which.

which(names(returns)==x)       # b

Another idea is to use grep

grep("^x$", colnames(returns)) # c
grep("^x$", names(returns))    # d
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Artem E
  • 369
  • 1
  • 4
  • 19
0

You can use [[ to values in the column based on the name of the column. If you don't want to quote the name of the column when calling the function, you have to use deparse and substitute.

test <- function(x) 
{ 
  xc <- deparse(substitute(x))
  returns[[xc]]
}

test(simple)
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168