Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Why does listing an element in a data frame by row name and component name return NA?

Tags:

r

I create a data frame dfrm with one column, and set the row names as so:

v1 = c(1,2,3)
dfrm <- data.frame(v1)
row.names(dfrm) <- c("AD","BP","CD")

dfrm
   v1
AD  1
BP  2
CD  3

I can access elements by row name and index:

dfrm$v1[1]
[1] 1

I can access elements by row name and component name in quotes:

dfrm["AD","v1"]
[1] 1

But why can't I access elements by row name and component name?

dfrm$v1["AD"]
[1] NA
like image 993
Justin Lilly Avatar asked Nov 13 '12 11:11

Justin Lilly


People also ask

What is the function to set row names for a data frame in R programming?

`. rowNamesDF<-` is a (non-generic replacement) function to set row names for data frames, with extra argument make.

What does row names mean in R?

rownames() function in R Language is used to set the names to rows of a matrix. Syntax: rownames(x) <- value.

Can a data frame element be a list?

Data frame columns can contain lists You can also create a data frame having a list as a column using the data. frame function, but with a little tweak. The list column has to be wrapped inside the function I.

What does Colnames mean in R?

The rownames() and colnames() functions in R are used to obtain or set the names of the row and column of a matrix-like object, respectively.


1 Answers

The answer is that vectors don't have rownames although they can have names.

When you access a column as a list item, R does not take the additional step of passing along the rownames to the names of the vector:

> dfrm$v1
[1] 1 2 3
> dfrm[["v1"]]
[1] 1 2 3
> dfrm[,"v1"]
[1] 1 2 3
> dfrm[,1]
[1] 1 2 3
> names(dfrm$v1)
NULL

Note that this is probably a good thing, as the cases where this is helpful are limited, and the overhead to copy the names every time a data.frame has a column pulled out likely not worth it.

If you want to copy them yourself:

> vone <- dfrm$v1
> names(vone) <- rownames(dfrm)
> vone
AD BP CD 
 1  2  3 
like image 130
Ari B. Friedman Avatar answered Oct 01 '22 10:10

Ari B. Friedman