0

I have a df looks like

df <- data.frame(Name = c("A", "A","A","B", "B", "C", "D", "E", "E"), 
                 Value = c(1, 1, 1, 2, 15, 3, 4, 5, 5))

Basically, A is 1, B is 2, C is 3 and so on. However, as you can see, B has "2" and "15"."15" is the wrong value and it should not be here.

I would like to find out the row which Value won't matches within the same Name. Ideal output will looks like

B  2
B  15
Marie
  • 71
  • 1
  • 6

3 Answers3

1

you can use tidyverse functions like:

df %>%
    group_by(Name, Value) %>% 
    unique()

giving:

    Name Value
1      A     1
2      B     2
3      B    15
4      C     3
5      D     4
6      E     5

then, to keep only the Name with multiple Value, append above with:

df %>%
  group_by(Name) %>%
  filter( n() > 1)
Aramis7d
  • 2,444
  • 19
  • 25
  • 2
    Base R translation - `df[with(df, ave(Value, Name, FUN=function(x) length(unique(x))) > 1 ),]` You could also take advantage of `n_distinct` - `df %>% group_by(Name) %>% mutate(nd=n_distinct(Value)) %>% filter(nd > 1)` – thelatemail Aug 25 '17 at 04:33
  • 1
    Or should I say `df %>% group_by(Name) %>% filter(n_distinct(Value) > 1)` to be even simpler. – thelatemail Aug 25 '17 at 05:39
  • This code save my life! Thank you! – Marie Aug 25 '17 at 07:18
0

Something like this? This searches for Names that are associated to more than 1 value and outputs one copy of each pair {Name - Value}.

df <- data.frame(Name = c("A", "A","A","B", "B", "C", "D", "E", "E"), 
                 Value = c(1, 1, 1, 2, 15, 3, 4, 5, 5))

res <- do.call(rbind, lapply(unique(df$Name), (function(i){
  if (length(unique(df[df$Name == i,]$Value)) > 1 ) {
    out <- df[df$Name == i,]
    out[!duplicated(out$Value), ]
  }
})))
res

Result as expected

  Name Value
4    B     2
5    B    15
Damiano Fantini
  • 1,925
  • 9
  • 11
0
   Filter(function(x)nrow(unique(x))!=1,split(df,df$Name))
$B
  Name Value
4    B     2
5    B    15 

Or:

Reduce(rbind,by(df,df$Name,function(x) if(nrow(unique(x))>1) x))

 Name Value
4    B     2
5    B    15
Onyambu
  • 67,392
  • 3
  • 24
  • 53