R - 使用变量访问数据框列

时间:2023-01-22 22:56:13

Consider the following code

请考虑以下代码

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

However the desired data frame is

但是,所需的数据框是

  col1 col2
1 1    4
2 2    5
3 3    6

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

此外,我希望能够做一些像d $ a这样的东西然后抓住d $ col1,因为a =“col1”

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

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

2 个解决方案

#1


24  

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

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

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"

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

你不能使用$来通过d $ a选择一列。 R将查找名称为a的列。相反,你可以做d [[a]]或d [,a]。

#2


10  

You can do it this way

你可以这样做

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

>d
  a b
1 1 4
2 2 5
3 3 6

#Renaming the columns
names(d) <- c(a,b)
> d
  col1 col2
1    1    4
2    2    5
3    3    6

#Calling by names
 d[,a]

#1


24  

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

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

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"

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

你不能使用$来通过d $ a选择一列。 R将查找名称为a的列。相反,你可以做d [[a]]或d [,a]。

#2


10  

You can do it this way

你可以这样做

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

>d
  a b
1 1 4
2 2 5
3 3 6

#Renaming the columns
names(d) <- c(a,b)
> d
  col1 col2
1    1    4
2    2    5
3    3    6

#Calling by names
 d[,a]