Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rle function in R for groups

Tags:

r

Below is how my data looks like.

City, count
Mexico, 1
Mexico, 1
London, 0
London, 1
London, 1

I am using Rle function to count the consistently in my values, but unable to apply the group logic.

I tried loop function, but it didn’t work.

I am looking for output like below

Mexico, 1:2
London, 0:1
London, 1:2
like image 350
Jay Avatar asked Aug 22 '26 22:08

Jay


1 Answers

data.table::rleid is a quick way to add a run ID variable to group by, after which aggregation is typical. You can borrow it for a dplyr context, if you like:

library(dplyr)

df <- data_frame(City = c("Mexico", "Mexico", "London", "London", "London"), 
                 count = c(1L, 1L, 0L, 1L, 1L))

df %>% 
    group_by(run = data.table::rleid(City, count), City) %>% 
    summarise(count = paste(count[1], n(), sep = ':'))
#> # A tibble: 3 x 3
#> # Groups:   run [?]
#>     run City   count
#>   <int> <chr>  <chr>
#> 1     1 Mexico 1:2  
#> 2     2 London 0:1  
#> 3     3 London 1:2

But this data isn't big enough to differentiate between ordinary and run grouping. Resampling it to make it more representative dataset,

set.seed(47)    # for reproducibility
df2 <- df %>% slice(sample(nrow(.), 10, replace = TRUE))

df2 %>% 
    group_by(run = data.table::rleid(City, count), City) %>% 
    summarise(count = paste(count[1], n(), sep = ':'))
#> # A tibble: 8 x 3
#> # Groups:   run [?]
#>     run City   count
#>   <int> <chr>  <chr>
#> 1     1 London 1:1  
#> 2     2 Mexico 1:1  
#> 3     3 London 1:2  
#> 4     4 London 0:1  
#> 5     5 London 1:1  
#> 6     6 Mexico 1:1  
#> 7     7 London 0:2  
#> 8     8 London 1:1

If you prefer, the same logic all in data.table:

library(data.table)

setDT(df2)[, 
           .(count = paste(count[1], .N, sep = ':')), 
           by = .(run = rleid(City, count), City)]
#>    run   City count
#> 1:   1 London   1:1
#> 2:   2 Mexico   1:1
#> 3:   3 London   1:2
#> 4:   4 London   0:1
#> 5:   5 London   1:1
#> 6:   6 Mexico   1:1
#> 7:   7 London   0:2
#> 8:   8 London   1:1

or base R:

df2$run <- data.table::rleid(df2$City, df2$count)

aggregate(count ~ City + run, df2, function(x) paste(x[1], length(x), sep = ':'))
#>     City run count
#> 1 London   1   1:1
#> 2 Mexico   2   1:1
#> 3 London   3   1:2
#> 4 London   4   0:1
#> 5 London   5   1:1
#> 6 Mexico   6   1:1
#> 7 London   7   0:2
#> 8 London   8   1:1
like image 181
alistaire Avatar answered Aug 25 '26 15:08

alistaire