使用变量访问数据框列 [英] access data frame column using variable

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

问题描述

考虑以下代码

a = "col1"
b = "col2"
d = data.frame(a=c(1,2,3),b=c(4,5,6))

此代码产生以下数据帧

  a b
1 1 4
2 2 5
3 3 6

但是所需的数据帧是

  col1 col2
1 1    4
2 2    5
3 3    6

此外,我希望能够执行 d $ a 之类的操作抓住 d $ col1 ,因为 a = col1

Further, I'd like to be able to do something like d$a which would then grab d$col1 since a = "col1"

如何告诉R a 是变量而不是列的名称?

How can I tell R that "a" is a variable and not a name of a column?

推荐答案

创建数据框后,您需要使用?名称。例如,您将拥有:

After creating your data frame, you need to use ?colnames. For example, you would have:

d = data.frame(a=c(1,2,3), b=c(4,5,6))
colnames(d) <- c("col1", "col2")

在创建数据框时,您也可以命名变量。例如:

You can also name your variables when you create the data frame. For example:

d = data.frame(col1=c(1,2,3), col2=c(4,5,6))

此外,如果您将列名存储在变量中,如

Further, if you have the names of columns stored in variables, as in

a <- "col1"

您不能使用 $ 通过 d $ a 选择列。 R将查找名称为 a 的列。相反,您可以执行 d [[a]] d [,a]

you can't use $ to select a column via d$a. R will look for a column whose name is a. Instead, you can do either d[[a]] or d[,a].

这篇关于使用变量访问数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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