2016-06-14 318 views
0

我需要在R中创建一个for循环来检查特定客户ID的权重值是否相等。For循环检查值是否相等

例如:

Cust# Weight 
1111 100 
1111 100 
1111 100 
1112 50 
1112 75 
1112 65 
1113 80 
1113 80 
1113 80 

在这个例子中,我会想返回记录的1111和1113,因为权重留在整个记录相同的客户。我不想要1112的记录,因为这三个记录的重量是波动的。

我知道这不应该太难,但我几乎没有for循环的经验。任何帮助将不胜感激。

+0

如果你可以开始某种编码,这将是有益的。 –

+2

此外,请提供所需的输出,因为它应该是什么混淆。 – lmo

+1

欢迎来到SO。请编辑您的问题以包含所需的输出。另外,如果有更好的方法可以执行,您是否真的需要for循环? – C8H10N4O2

回答

0

有很多方法可以做到这一点,这里有一个data.table解决方案:

library(data.table) 

df <- data.table(cust = rep(1111:1113, each=3), 
       weight = c(rep(1000, 3), 50, 75, 65, rep(80,3))) 

df[, count := .N, keyby = .(cust, weight)][count==1, .(cust, weight)] 

编辑:dplyr之一:

library(dplyr) 
df %>% group_by(cust) %>% filter(n_distinct(weight)==1) %>% distinct(cust, weight) 
+0

或'df [,count:= .N,keyby =。(cust,weight)] [count == 1,-c(“count”),with = FALSE]' – C8H10N4O2

+0

我们中的一个似乎误解了期望OP的输出。我们的输出是互补的......我试着再次阅读这个问题,并且我保留OP想要删除非重复条目的印象,但我当然可能是错的。 – RHertel

+2

或者只是'df [,if(uniqueN(weight)== 1L).SD,by = cust]' –

1

下面是与基础R一种可能性:

df1[df1$Cust %in% df1$Cust[duplicated(df1)],] 
# Cust Weight 
#1 1111 100 
#2 1111 100 
#3 1111 100 
#7 1113  80 
#8 1113  80 
#9 1113  80 

补充部分data.frame可以通过添加一个否定!操作来获得:

df1[!df1$Cust %in% df1$Cust[duplicated(df1)],] 
# Cust Weight 
#4 1112  50 
#5 1112  75 
#6 1112  65 

其产生在这个例子中相同的结果更一般的版本可以是在本实施例中使用

var.rows <- aggregate(Weight ~ Cust, df1, var) 
df1[df1$Cust %in% var.rows$Cust[!var.rows$Weight],] 

数据:

df1 <- structure(list(Cust = c(1111L, 1111L, 1111L, 1112L, 1112L, 1112L, 
       1113L, 1113L, 1113L), Weight = c(100L, 100L, 100L, 50L, 75L, 
       65L, 80L, 80L, 80L)), .Names = c("Cust", "Weight"), 
       class = "data.frame", row.names = c(NA, -9L)) 
0

你可以SE总让每个客户独特的配重的数量,并用它来找到这些条目:

a <- aggregate(Weight ~ Cust, data=x, FUN=function(y) length(unique(y))) 
a$Cust[a$Weight==1] 
## [1] "1111" "1113" 
1

我们可以通过使用uniqueN

library(data.table) 
setDT(df1)[, if(uniqueN(Weight)==1) .SD , Cust] 
# Cust Weight 
#1: 1111 100 
#2: 1111 100 
#3: 1111 100 
#4: 1113  80 
#5: 1113  80 
#6: 1113  80 

或期权base R

i1 <- rowSums(table(df1)!=0)==1 
subset(df1, Cust %in% names(i1)[i1])