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

Time:10-18

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.

CodePudding user response:

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)))
  •  Tags:  
  • r
  • Related