如何使用两个变量计算表中的行

时间:2017-09-08 00:52:08

标签: r count

我有一个名为dF的数据框,有两列:Name,Region。例如,

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

如果我做表(dF),它将显示一个包含两个变量的表。比如像这样

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

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

如何计算特定变量的行数?例如,只需获取表格列中AM Region变量显示的数字三次。

1 个答案:

答案 0 :(得分:2)

示例:

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

因此,在您的情况下,您需要将结果表存储到变量中,并且应该执行以下操作:

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