如何访问此表的列?

时间:2014-10-03 19:52:43

标签: r dataframe

这是我的变量tv.table,打印:

> tv.table
 sex.permuted
        B   G
  d    87  94
  dvm  49  52
  l   249 277
  lvm 197 193
  n   143 139

我想只访问tv.table的列。通常,我会使用命令tv.table $ B和tv.table $ G执行此操作。但是,这是行不通的,我怀疑是因为B标题上面的列标题和G标记为sex.permuted。我该如何摆脱它?

1 个答案:

答案 0 :(得分:2)

这似乎是一个R表对象。它的维度具有dimname,然后是列名和rownames。由于它们确实是矩阵,因此访问方法是通过" ["功能:

> with(airquality,
+    table(OzHi = Ozone > 80, Month, useNA = "ifany"))
       Month
OzHi     5  6  7  8  9
  FALSE 25  9 20 19 27
  TRUE   1  0  6  7  2
  <NA>   5 21  5  5  1
> attributes( with(airquality,
+    table(OzHi = Ozone > 80, Month, useNA = "ifany")) )
$dim
[1] 3 5

$dimnames
$dimnames$OzHi
[1] "FALSE" "TRUE"  NA     

$dimnames$Month
[1] "5" "6" "7" "8" "9"


$class
[1] "table"

因此,要访问第一列和第二列,请按字符名称引用它们:

> airtbl <-  with(airquality,
+    table(OzHi = Ozone > 80, Month, useNA = "ifany"))

> airtbl[ , c("5","6")]
       Month
OzHi     5  6
  FALSE 25  9
  TRUE   1  0
  <NA>   5 21
相关问题