21

From the reading I've been doing with R, I can select a column in a data frame by either of these two methods: frame[,column] or frame$column. However, when I have a string as a variable, it works only in the first. In other words, consider the following:

I have a data frame, tmp, a subset of a larger data frame of question responses. V1 is the responder's id, Q5.3 is the response, a 1 or 0:

            V1 Q5.3
2 R_bdyKkzWcvBxDFTT    1
3 R_41wnKUQcM8mUW2x    0
4 R_2ogeykkgbH2e4RL    1
5 R_8D4jzMBfYO0M0ux    1
6 R_3KPgP2pxWROnip7    1

str(tmp)

'data.frame':   5 obs. of  2 variables:
     $ V1  : Factor w/ 364 levels "R_0039orNoOoWaDQx",..: 256 116 70 201 95
     $ Q5.3: num  1 0 1 1 1

Now, I define a variable x, that holds the string of the name of one of the columns.

x<-"Q5.3"

tmp[,x] returns what I think it should return:

tmp[,x]

[1] 1 0 1 1 1

tmp$"Q5.3" returns what I think it should return:

tmp$"Q5.3"

[1] 1 0 1 1 1

tmp$x however returns

tmp$x

NULL

How can I tell R to interpret tmp$x as tmp$"Q5.3".

0

1 Answer 1

34

If you have a variable x with a column name in tmp, tmp[,x] or tmp[[x]] are the correct ways to extract it. You cannot get R to treat tmp$x as tmp$"Q5.3". tmp$x will always refer to the item named "x" in "tmp".

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

11 Comments

this has got to be a dupe ...
@BenBolker I can never find a good dup for this question even though it comes up soooooo often. I was thinking of starting one. "What's the difference between $, [], and [[]] when working with data.frames?"
Do you know where this is discussed in any documentation? I couldn't find it anywhere, and have wasted a bit of time trying things like parse() and such...
Thx. I'm not surprised that browsing the questions didn't turn it up.
@BenBolker Here are a couple, stackoverflow.com/questions/19730806/…, stackoverflow.com/questions/18222286/…. The latter seems to have more closed questions pointing to it.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.