如何对具有两个变量的表中的行进行计数 [英] How to count rows in a table with two variables

查看:83
本文介绍了如何对具有两个变量的表中的行进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为dF的数据框,其中有两列:名称,区域。例如,

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

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

如果我使用table(dF),它将显示有两个变量的表。例如这样的

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

如何仅计算特定变量的行数?例如,仅获得表列中AM Region变量出现三号的次数。

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.

推荐答案

示例:

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)

这篇关于如何对具有两个变量的表中的行进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆