1
data <- c( 1, 2, 4, 5, 6, 1, 2, 2, 4, 5)
data_table <- table(data)
class(data_table)
# [1] "table"

data_table
# data
# 1 2 4 5 6 
# 2 3 2 2 1 

I think the row of numbers (1 2 3 4 5 6) are the names for each column. The second row of numbers are numeric.

Now I do not know how to extract the second row of numbers from this table. For example,

data_table[1]
# 1 
# 2 

class(table_data[1])
# [1] "integer"

Now I want to get the number 2 in the first element of this table. I tried several ways and all failed. I am a beginning learner for R language. Could anyone explain the method and reason? Any help is appreciated.

hong
  • 51
  • 1
  • 4

1 Answers1

3

An "table" object is not an atomic vector. Atomic vectors do not have attributes other than names, whereas tables have both dimensions and dimnames.

> attributes(data_table)
$dim
[1] 5

$dimnames
$dimnames$data
[1] "1" "2" "4" "5" "6"


$class
[1] "table"

The indexing of table objects is very much like that of R arrays.

> new_arr <- array(NA, 5)
> dim(new_arr)
[1] 5
> attributes(new_arr)
$dim
[1] 5

The dim attribute will "drop" off when indexed unless drop=FALSE is used, and when it is used, the correspondence with R 'array`s becomes even more obvious:

> class( data_table[2])
[1] "integer"
> class( data_table[2,drop=FALSE])
[1] "array"
IRTFM
  • 258,963
  • 21
  • 364
  • 487