Reputation: 756
My question seems to be easy but difficult to describe, see the code below. Let's create a data frame first:
Length<-c(10,11,9,8,10)
Width<-c(5,5.4,4.7,5.6,6.1)
Layer<-c(8,10,12,10,14)
data<-data.frame(Length, Width, Layer)
data
Length Width Layer
1 10 5.0 8
2 11 5.4 10
3 9 4.7 12
4 8 5.6 10
5 10 6.1 14
And as we all know, if we'd like to indicate variable from a given data frame, we need to type as below:
data$Layer
[1] 8 10 12 10 14
However, when there are many variables it becomes time consuming so I'd like to find other ways:
var_list<-c("Length", "Width", "Layer")
var_list
[1] "Length" "Width" "Layer"
> var_list[1]
[1] "Length"
> var_list[2]
[1] "Width"
> var_list[3]
[1] "Layer"
So a variable list is created, and I'd like to use this to indicate to the data set but in vain:
> data$var_list
NULL
> data$var_list[1]
NULL
> data$var_list[2]
NULL
> data$var_list[3]
NULL
Hope my description is clear enough and thanks in advance for any ideas or suggestions.
Upvotes: 1
Views: 70
Reputation: 35324
1: you can get the names of the columns via the names()
function:
names(data);
## [1] "Length" "Width" "Layer"
2: You can extract a single column using the `[[`()
operation:
data[['Layer']];
## [1] 8 10 12 10 14
data[[names(data)[3L]]];
## [1] 8 10 12 10 14
3: But since you end up using a numeric index into the vector of names anyway, I suggest you simply use numeric indexing on the original data.frame:
data[[3L]];
## [1] 8 10 12 10 14
Upvotes: 2