[R] specifying column names in a vector of characters and the use?

Erik Iverson eriki at ccbr.umn.edu
Mon Jul 19 04:19:40 CEST 2010


Hello,

> What I would like to do is have a data.frame with column names and have
> these column names stored as strings in another vector.  Then I would like
> to be able to access the data.fram columns via referencing the vector of
> names.  The code below shows the last few executions that failed to retrieve
> the values for column named X1.  Seth
>
>
>> table.1<-cbind(c(1,2,3,2,2),c(0,9,0,7,9),c(7,5,9,8,8))
>> table.1
>       [,1] [,2] [,3]
> [1,]    1    0    7
> [2,]    2    9    5
> [3,]    3    0    9
> [4,]    2    7    8
> [5,]    2    9    8

See easier way to construct your object below.

<snip>
> [1] "X1"
>> table.1$hold[1] # FROM HERE DOWN ARE MY ATTEMPTS TO ACCESS X1
> NULL
>> table.1$(hold[1])
> Error: unexpected '(' in "table.1$("
>> table.1$get(hold[1])
> Error: attempt to apply non-function
>> table.1$(get(hold[1]))
> Error: unexpected '(' in "table.1$("

You need to index with ?[

Here is a complete example:

table.1<- data.frame(X1 = c(1,2,3,2,2),
                      X2 = c(0,9,0,7,9),
                      X3 = c(7,5,9,8,8))

hold <- names(table.1)

## to return a data.frame
table.1[hold[1]]

## to return a vector
table.1[[hold[1]]]



More information about the R-help mailing list