如何使用$ notation [duplicate]使用字符串变量来选择数据框列

时间:2022-04-18 04:49:20

This question already has an answer here:

这个问题在这里已有答案:

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:

从我用R做的读数,我可以通过以下两种方法之一在数据框中选择一列:frame [,column]或frame $ column。但是,当我将一个字符串作为变量时,它只能在第一个字符串中起作用。换句话说,请考虑以下事项:

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:

我有一个数据框,tmp,一个较大的问题响应数据框的子集。 V1是响应者的id,Q5.3是响应,1或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,它保存其中一列的名称字符串。

x<-"Q5.3"

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

tmp [,x]返回我认为它应该返回的内容:

tmp[,x]

[1] 1 0 1 1 1

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

tmp $“Q5.3”返回我认为它应该返回的内容:

tmp$"Q5.3"

[1] 1 0 1 1 1

tmp$x however returns

但是tmp $ x会返回

tmp$x

NULL

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

如何告诉R将tmp $ x解释为tmp $“Q5.3”。

1 个解决方案

#1


18  

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

如果在tmp中有一个带有列名的变量x,则tmp [,x]或tmp [[x]]是提取它的正确方法。你不能让R使用tmp $ x作为tmp $“Q5.3”。 tmp $ x将始终引用“tmp”中名为“x”的项目。

#1


18  

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

如果在tmp中有一个带有列名的变量x,则tmp [,x]或tmp [[x]]是提取它的正确方法。你不能让R使用tmp $ x作为tmp $“Q5.3”。 tmp $ x将始终引用“tmp”中名为“x”的项目。