dataframe - R how use a string variable to select a data frame column using $ notation -
this question has answer here:
from reading i've been doing r, can select column in data frame either of these 2 methods: frame[,column] or frame$column. however, when have string variable, works in first. in other words, consider following:
i have data frame, tmp, subset of larger data frame of question responses. v1 responder's id, q5.3 response, 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, define variable x, holds string of name of 1 of columns.
x<-"q5.3"
tmp[,x] returns think should return:
tmp[,x] [1] 1 0 1 1 1
tmp$"q5.3" returns think should return:
tmp$"q5.3" [1] 1 0 1 1 1
tmp$x returns
tmp$x null
how can tell r interpret tmp$x tmp$"q5.3"
thanks!
if have variable x
column name in tmp
, tmp[,x]
or tmp[[x]]
correct way extract it. cannot r use treat tmp$x
tmp$"q5.3"
. tmp$x
refer item named "x" in "tmp".
Comments
Post a Comment