Günal
Günal

Reputation: 115

Referring to variables by column names

I have a matrix, say X, whose columns I need to use in R. I named each column using the colnames command. However, when I type the name of a column, nothing comes up. To illustrate, I used a code like the one below:

colnames(X) <- c("column1","column2")

When I type X, column1 and column2 appear at the top of the columns. However, when I type column1 or column2, they cannot be found.

Does anyone know what needs to be done?

Upvotes: 2

Views: 50800

Answers (2)

Se&#241;or O
Se&#241;or O

Reputation: 17432

This is a fairly basic part of R, when you have a column name, row name, list element name, etc., you have to tell R the object to look inside first.

In your case, you would have to do:

X[,"column1"] 

to get column1.

A better option for you is a data.frame:

X <- data.frame(Column1 = c(....), Column2 = c(....))
X$Column1 #Returns "Column1"

In both cases you're now correctly telling R to look for something named column1 inside of X.

As Matthew states below, if you need to call column without referring to X, you can use attach(X) first. Most people tend to avoid this, as it creates a new copy of the element - and that can get messy if you end up changing column1

Upvotes: 8

Matthew Lundberg
Matthew Lundberg

Reputation: 42689

Here's such a matrix:

X <- matrix(1:6, ncol=2)

colnames(X) <- c("column1","column2")
X
     column1 column2
[1,]       1       4
[2,]       2       5
[3,]       3       6

attach(as.data.frame(X))
column1
[1] 1 2 3

Upvotes: 3

Related Questions