stackbeats
stackbeats

Reputation: 173

How to count rows in a table with two variables

I have a dataframe called dF with two columns: Name, Region. For instance,

Name Region
a    EU
a    EU
b    AM
C    AP
...  ...

If I do table(dF), it will show a table with two variables. For instance like this

'table' int [1:325,1:3]

        Region
Name    EU  AM  AP
a       2   0   0
b       0   1   0
c       0   0   1

How do I count the number of rows for only specific variables? For instance, just getting how many times the number three appears for the AM Region variable in the table column.

Upvotes: 0

Views: 2282

Answers (1)

Imran Ali
Imran Ali

Reputation: 2279

Example:

result <- table(state.division, state.region)  #Sample data 
result #will return data like shown below

        state.region
state.division       Northeast South North Central West
  New England                6     0             0    0
  Middle Atlantic            3     0             0    0
  South Atlantic             0     8             0    0
  East South Central         0     4             0    0
  West South Central         0     4             0    0
  East North Central         0     0             5    0
  West North Central         0     0             7    0
  Mountain                   0     0             0    8
  Pacific                    0     0             0    5

  sum(result[,2]==4) #to count 4's in second column

So in your case you need to store the resulting table to a variable, and the following should do it:

result <- table(dF)
sum(result[,2]==3)

Upvotes: 3

Related Questions