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

How can I easily see if a value in a column changes per another value?

Sorry if the title is confusing, but it should be a simple solution. I have a large dataframe and I want to see if the city changes per the persons name.

Here is an example of my dataset:

> dput(df)
structure(list(Name = c("John Smith", "John Smith", "John Smith", 
"John Smith", "John Smith", "John Smith", "Richard", "Richard", 
"Richard", "Richard", "Richard", "Richard", "Richard"), City = c("Boston", 
"Boston", "Boston", "Boston", "Boston", "New York", "Los Angeles", 
"Los Angeles", "Los Angeles", "Los Angeles", "Los Angeles", "Los Angeles", 
"New York")), class = "data.frame", row.names = c(NA, -13L))

As we can see, John Smith has resided in Boston except for one instance where he lived in New York. For my large dataset it isn’t obvious if the city changes per name, so I was wondering if there is an easier way to check for this.

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 :

We can group by ‘Name’, get the distinct count of rleid of ‘City’

library(dplyr)
library(data.table)
df %>% 
   group_by(Name) %>%
   summarise(n = n_distinct(rleid(City)))

Or with base R

with(df, tapply(City, Name, FUN = \(x) length(rle(x)$values)))
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