George Self George Self - 3 months ago 7
R Question

Extracting Elements from a Table in R

I've looked online for more than two hours for help with this, and "played around" with various parameters, and cannot seem to figure this out. I have a database, hlc, that includes a nominal variable named "loc." That variable is a numeric code where each code describes a college's location, like "rural" or "small city." I need to get a count for each of those categories.

I created a table:

table(hlc$loc)

-3 11 12 13 21 22 23 31 32 33 41 42 43
0 9 12 27 14 3 5 1 17 39 39 10 2


I then placed that table into a variable:

loc <- table(hlc$loc)


I can get any one of the elements like this:

loc[1]
-3
0


What I would like to do is get each element individually, like "-3" and "0" for
loc[1]
. I tried this, unsuccessfully:

loc[1,1]
Error in `[.default`(loc, 1, 1) : incorrect number of dimensions


It seems like the
loc
table is a list, but each element in that list is somehow linked to two values, the bin number and the count of instances for that bin. How can I extract each of those individual values from the table: the bin number and the count for that bin?

Thanks for any help you can offer.

Answer

You can access it like:

names(loc[2])
11

loc[[2]]
9
Comments