R Why enumerating an element in a data frame by row name and component name returns NA?

I create a dfrm data frame with one column and set the row names like this:

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 name and row index:

 dfrm$v1[1] [1] 1 

I can access the elements by string name and component name in quotation marks:

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

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

 dfrm$v1["AD"] [1] NA 
+7
source share
1 answer

The answer is that vectors do not have growth names, although they may have names.

When you access a column as a list item, R does not take the additional step of going through the names of the growths 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 good, since the cases where it is useful are limited, and the overhead of copying names every time the data.frame has an output column is probably not worth it.

If you want to copy them yourself:

 > vone <- dfrm$v1 > names(vone) <- rownames(dfrm) > vone AD BP CD 1 2 3 
+5
source

All Articles