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

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

问题描述

考虑以下代码

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

此代码生成以下数据框架

This code produces the following data frame

  a b
1 1 4
2 2 5
3 3 6

然而,所需的数据框是

  col1 col2
1 1    4
2 2    5
3 3    6

此外,我想要做一些像 d $ a 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?

推荐答案

创建数据框后,需要使用?colnames 。例如,您将具有:

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))

此外,如果您将列的名称存储在变量中, / p>

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

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

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