我的样本数据集
df <- data.frame(period=rep(1:3,3),
product=c(rep('A',9)),
account= c(rep('1001',3),rep('1002',3),rep('1003',3)),
findme= c(0,0,0,1,0,1,4,2,0))我想要的输出数据集
output <- data.frame(period=rep(1:3,2),
product=c(rep('A',6)),
account= c(rep('1002',3),rep('1003',3)),
findme= c(1,0,1,4,2,0))这里我的条件是..。我想消除记录,3记录,从9基于以下条件。
规则1:应满足周期1、2、3规则2:所有期间的查找值=0规则3:所有这3项记录(前1、2、3)应有相同的积规则4:所有这3次重计(周期1、2、3)应有一个帐户。
发布于 2017-09-16 04:57:52
如果我正确理解,如果所有的句点都包含在这个组合中,您希望删除所有来自产品帐户组合的所有记录,其中findme == 0吗?
library(dplyr)
df %>%
group_by(product, account, findme) %>%
mutate(all.periods = all(1:3 %in% period)) %>%
ungroup() %>%
filter(!(findme == 0 & all.periods)) %>%
select(-all.periods)
# A tibble: 6 x 4
period product account findme
<int> <fctr> <fctr> <dbl>
1 1 A 1002 1
2 2 A 1002 0
3 3 A 1002 1
4 1 A 1003 4
5 2 A 1003 2
6 3 A 1003 0发布于 2017-09-16 05:33:19
下面是data.table的一个选项
library(data.table)
setDT(df)[df[, .I[all(1:3 %in% period) & !all(!findme)], .(product, account)]$V1]
# period product account findme
#1: 1 A 1002 1
#2: 2 A 1002 0
#3: 3 A 1002 1
#4: 1 A 1003 4
#5: 2 A 1003 2
#6: 3 A 1003 0https://stackoverflow.com/questions/46250129
复制相似问题