开发者

Pull column from table using header?

Given a table of the form:

  a b c
X1 0 1 0
X2 1 0 0
X3 1 0 0

In order to pull a column from the table:

col.1 <- table$a

Assume you have a variable:

col.name <- 'a'

col.1 <- table$col.name

Why doesn't this work? Is there a way to make开发者_JAVA百科 this work?


It doesn't work because the "$" operator does not evaluate its argument. What you need is to use "[" or "[[". (It's not a good idea to call your table. "table". It confuses users who use the table function.)

table <- structure(c(0, 1, 1, 1, 0, 0, 0, 0, 0), .Dim = c(3L, 3L), .Dimnames = list(
    c("X1", "X2", "X3"), c("a", "b", "c")), class = "table")
table[ , col.name]
# X1 X2 X3 
#  0  1  1
table[ , "a"]
# X1 X2 X3 
#  0  1  1  
table
table[["a"]]
Error in table[["a"]] : subscript out of bounds


table[[col.name]]

will work anywhere the $ operator will work (lists and derived classes like data frames). The issue is that the $ way of accessing lists and data frames is more of a shortcut that treats whatever is after it as a character string. If you want to use a character string that is the result of evaluated code you have to use some sort of bracket notation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜