如何计算符合条件的行 [英] How to count rows meeting a condition

查看:53
本文介绍了如何计算符合条件的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下数据框:

Suppose I have the following data frame:

Data1
      X1     X2
1     15     1
2     3      1
3     7      0
4     11     1
5     1      0
6     9      0
7     18     0
8     6      1
9     3      1

我想知道如何找到 X1 大于9且 X2 等于1吗?

I would like to know how to find the total number of observations where X1 is greater than 9 and X2 is equal to 1?

我认为我需要使用 sum(),但是我不知道在括号中放什么。

I think I will need to use sum(), but I have no idea what to put in the parenthesis.

推荐答案

data1='
        X1     X2
        15     1
        3      1
        7      0
        11     1
        1      0
        9      0
        18     0
        6      1
        3      1'



data1=read.table(text=data1,header=T)    

1)

nrow(data1[data1$X1 > 9 & data1$X2 ==1,])

2)

sum(data1$X1 > 9 & data1$X2 ==1)

3)

With data.table:

dataDT = data.table(data1)
dataDT[X1 > 9 & X2 == 1, .N]

这篇关于如何计算符合条件的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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