如何使用字符串变量使用 $ 表示法选择数据框列 [英] How to use a string variable to select a data frame column using $ notation

查看:24
本文介绍了如何使用字符串变量使用 $ 表示法选择数据框列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我一直在用 R 进行的阅读,我可以通过以下两种方法之一在数据框中选择一列:frame[,column]frame$column.但是,当我有一个字符串作为变量时,它只适用于第一个.换言之,请考虑以下事项:

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:

我有一个数据框 tmp,它是一个更大的问题响应数据框的子集.V1 是响应者的 id,Q5.3 是响应,1 或 0:

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

现在,我定义了一个变量 x,它保存其中一列的名称字符串.

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

x<-"Q5.3"

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

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

tmp[,x]

[1] 1 0 1 1 1

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

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

tmp$"Q5.3"

[1] 1 0 1 1 1

tmp$x 然而返回

tmp$x

NULL

我如何告诉 R 将 tmp$x 解释为 tmp$"Q5.3".

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

推荐答案

如果你有一个变量 xtmp, tmp[,x]tmp[[x]] 是提取它的正确方法.您不能让 R 将 tmp$x 视为 tmp$"Q5.3".tmp$x 将始终引用tmp"中名为x"的项目.

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".

这篇关于如何使用字符串变量使用 $ 表示法选择数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆