Home > Back-end >  Is there a simpler way to do this? Trying to find specific associations and having R point out where
Is there a simpler way to do this? Trying to find specific associations and having R point out where

Time:10-27

So, let's say that I have the following data frame:

df1 <- data.frame(var = c('A', 'A', 'A', 'A', 'D', 'A', 'A', 'A', 'A', 'A'), 
                  res = c(100, 100, 100, 100, 100, 100, 101, 101, 101, 101))

My actual dataset is a lot bigger. I want R to identify D100 as being the odd one out. For that, I did:

df2 <- df1 %>%
  group_by(var, res) %>% 
  summarise(total_count=n()) %>% drop_na() %>%
  group_by(res) %>% 
  summarise(total_count=n())

df3 <- df2[df2$total_count>1, ] 

Which then tells me that it is the value 100 that appears twice associated with two letters. Is there a way to simplify this? In particular, it would be great if I could ask R "which number is associated with more than one category?" and point out exactly the entry in the data frame where that happens. This code does that trick but it looks messy to me and it doesn't exactly tell me where in the data frame that was, just points me in the right direction.

CodePudding user response:

You can do two counts and filter:

library(dplyr)
df1 %>% 
  count(res, var) %>% 
  count(res)
#  res n
#1 100 2
#2 101 1

df1 %>% 
  count(res, var) %>% 
  count(res) %>% 
  filter(n > 1)
#  res n
#1 100 2

To spot the row, you could use interaction:

df1[interaction(df1) == names(which(table(interaction(df1)) == 1)), ]

#  var res
#5   D 100
  • Related