0

I have a function that takes as input a specific column name. I then want to grab the column of a data frame that corresponds to that name. The problem is if I have code like this:

New <- function(name) { dataframe$name }

then it looks for the column with the name "name" and not the name I input in the function. Is there any way to get around this?

1
  • 7
    Use: New <- function(name) { dataframe[, name] } Commented Jul 9, 2013 at 16:19

2 Answers 2

2

Just to add my 5c. Two alternatives above behave differently when the column with the given name does not exist. This may be important for what you do.

dataframe[, name] 

will return an error, while

dataframe[[name]] 

will return NULL

Sign up to request clarification or add additional context in comments.

Comments

1

As Tyler mentioned in a comment

New <- function(name) { dataframe[, name] }

or, alternatively,

New <- function(name) { dataframe[[name]] }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.