Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a simpler way to do this? Trying to find specific associations and having R point out where it is in the data frame

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading