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".
We can select a variable from a data frame using select() function in two ways. One way is to specify the dataframe name and the variable/column name we want to select as arguments to select() function in dplyr. In this example below, we select species column from penguins data frame.
To access a specific column in a dataframe by name, you use the $ operator in the form df$name where df is the name of the dataframe, and name is the name of the column you are interested in. This operation will then return the column you want as a vector.
If you want to add multiple variables, you can do this with a single call to the assign method. Just type the name of your dataframe, call the method, and then provide the name-value pairs for each new variable, separated by commas.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With