【发布时间】:2015-09-02 10:02:04
【问题描述】:
我有一个df如下:
data
names fruit
7 john apple
13 john orange
14 john apple
2 mary orange
5 mary apple
8 mary orange
10 mary apple
12 mary apple
1 tom apple
6 tom apple
我想做两件事。首先,计算同时具有苹果和橙子的独特观察的数量(即 2 玛丽和约翰)。
然后,我想从我的数据框中删除它们,这样我就只剩下只有苹果的独特个人了。
这是我尝试过的
toremove<-unique(data[data$fruit=='apple' & data$fruit=='orange',"names"]) ##this part doesn't work, if it had I would have used the below code to remove the names identified
data2<-data[!data$names %in% toremove,]
真的,我想使用 grepl,因为我的真实数据比水果复杂一点。这是我尝试过的(先转换为data.table)
data1<-data.table(data1)
z<-data1[,ind := grepl('app.*? & orang.*?', fruit), by='names'] ## this works fine when i just use 'app.*?' but collapses when I try to add the & sign, so I'm making an error with the operator. In addition the by='names' doesn't work out for me, which is important. My plan here was to create an indicator (if an individual has an apple and an orange, then they get an indicator==1 and I would then filter them out on the basis of this indicator).
所以,总而言之,我的问题在于识别同时拥有苹果和橙子的人。这看起来很简单,所以请随时将我引导到可以教我这个的资源!
期望的输出
names fruit
1 tom apple
6 tom apple
【问题讨论】:
-
所以你想要的输出不包括独特观察的计数?那么,为什么要首先计算呢?
-
我想计算有多少人同时拥有苹果和橙子。如果我有一个针对这些条件的指标,我将对其进行子集化并计算它们。或者,我可以将我的 df 限制为只有苹果和橙子的人,并计算其中独特的人的数量。然后当我得到只有苹果人的最终输出时,一个简单的减法会告诉我有多少人同时拥有橙子和苹果。所以真的,我专注于如何识别苹果和橙子的人。在那之后我可以计算出如何计算它们。
标签: r operators data.table grepl