通过使用R中的条件来计数变量 [英] count a variable by using a condition in R
本文介绍了通过使用R中的条件来计数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是R的新人。我有一个包含3列的数据框。
第一个显示ID,对于每个家庭,我们有一个uniqe ID。其他列显示关系(父亲为1,母亲为2,孩子为3,第三列显示他们的年龄)
现在我想知道每个家庭有多少双胞胎(双胞胎是同龄的孩子在每个家庭)
我的数据框:
I am new in R . I have a data frame containing 3 columns. first one shows ID , for each household we have a uniqe ID. the other columns shows relationship(1 for father , 2 for mother and 3 for children . third columns shows their age. now i want to know how many twins are there in each family. ( twins are childs that have same age in each family) my data frame:
Id relationship age
1001 1 60
1001 2 50
1001 3 20
1002 1 70
1002 2 68
1002 3 23
1002 3 27
1002 3 27
1002 3 23
1003 1 60
1003 2 40
1003 3 20
1003 3 20
结果:
id twins
1001 0
1002 2
1003 1
推荐答案
aggregate
> aggregate(age ~ Id, function(x) sum(duplicated(x)), data=df[df[,2]==3, ])
Id age
1 1001 0
2 1002 2
3 1003 1
这篇关于通过使用R中的条件来计数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文