Bach
Bach

Reputation: 6217

Accessing a named column of a data frame using a variable which holds the name

Suppose data is a data.frame. I wish to access data$field, without knowing the name field in advance; instead, I have a variable varfield which holds the string 'field', and I wish to use that variable to access the column in data whose name is the value of varfield.

Can this be done?

Upvotes: 0

Views: 66

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61154

Try using [ instead of $ and use varfield for subseting, just like this:

data[,varfield]

Upvotes: 1

Related Questions