How to access values ​​in a frequency table

I have a frequency table that counts the frequency of elements in a vector

a = table(c(0,1,1,1,0,2,2,4,1,2,3,2,1,2,3,1,1,1,2,3,4,1,1,0)) a # 0 1 2 3 4 # 3 10 6 3 2 

I know that I can get the name by name (s). But when I tried to access the SECOND values ​​of the string

 a[1, "0"] # Error in a[1, "0"] : incorrect number of dimensions a[1, 1] # Error in a[1, 1] : incorrect number of dimensions 
+6
source share
4 answers

This table is actually an array.

 x <- c(0,1,1,1,0,2,2,4,1,2,3,2,1,2,3,1,1,1,2,3,4,1,1,0) (a <- table(x)) # # 0 1 2 3 4 # 3 10 6 3 2 class(unclass(a)) # [1] "array" 

His names are on top, and the meanings below.

 names(a) [1] "0" "1" "2" "3" "4" 

You can access your items in several ways.

 a[1] ## access named element by index # 0 # 3 a[[1]] ## access unnamed element by index # [1] 3 a["0"] ## access named element by name # 0 # 3 a[["0"]] ## access unnamed element by name # [1] 3 as.vector(a) ## as.vector() drops table down to unnamed vector # [1] 3 10 6 3 2 c(a)[2:4] ## c() drops table down to named vector # 1 2 3 # 10 6 3 class(a[2:4]) # [1] "array" class(c(a)[2:4]) # [1] "integer" 

It also has the nrow and dim attribute, which is configured on the last few lines of table .

 y <- array(tabulate(bin, pd), dims, dimnames = dn) class(y) <- "table" 

Although I really do not understand why nrow(a) is 5, but a[1,] returns an error.

+7
source

The table() command returns a named vector, not a matrix or data.frame. If you want to access the number of zeros, you would do

 a["0"] 

Please note that the numeric properties of the levels are lost, because the names of the named vectors must be characters. You can convert them using as.numeric(names(a)) if you like

+4
source

The table you use is a one-dimensional array, and you use 2 dimensions to retrieve the element that you get this error.

Use something like [1]

+2
source

a = as.numeric (names (a))

he will give you access to the first column

+1
source

Source: https://habr.com/ru/post/978770/


All Articles