George Self
George Self

Reputation: 67

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?

Upvotes: 2

Views: 3402

Answers (2)

dww
dww

Reputation: 31452

The other answers already tell you how to access the values you want. But it is worth adding a little explanation, so that you also understand what is going on.

When you print loc it looks like you get two rows of numbers. But this is misleading. The top row is actually an attribute that provides the names of each element, and it consists of character strings, not numbers. We can use str to see the structure more clearly:

set.seed(123)
x=sample(c(-3,1,4,5,7,11),50,T)
loc=table(x)
str(loc)
# 'table' int [1:6(1d)] 8 9 8 7 7 11
# - attr(*, "dimnames")=List of 1
#  ..$ x: chr [1:6] "-3" "1" "4" "5" ...

Because loc is a named vector, we can use the names to access elements. But with a little care. Notice that referring to elements by their index position and their name gives different results

loc[1]
#-3 
# 8 

loc["1"]
#1 
#9

Upvotes: 2

HubertL
HubertL

Reputation: 19544

You can access it like:

names(loc[2])
11

loc[[2]]
9

Upvotes: 5

Related Questions