Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

R: group_by() column1 and perform rle() on column2 #6997

Closed
davidss101 opened this issue Feb 29, 2024 · 4 comments
Closed

R: group_by() column1 and perform rle() on column2 #6997

davidss101 opened this issue Feb 29, 2024 · 4 comments

Comments

@davidss101
Copy link

Hello Everyone,

I was wondering if people could help with this problem. I am trying to use group_by() and rle() in R to group according to column1 and count the consecutive number of times there is either a one or a zero within each group from column2. I would like to return both the "values" and "lengths" data from using rle().

This is what my data frame (df1) looks like:

Screenshot 2024-02-29 at 4 20 49 PM

I used this code to generate what I thought might work based on some suggestions I found on the web.

df2 <- df1 %>% group_by(column1) %>% reframe(data.frame(unclass(rle(df1$column2))))

This is the output I get for df2:

Screenshot 2024-02-29 at 4 24 43 PM

It seems that my code is not grouping the data effectively according to column1. Any suggestions would be appreciated. Thanks.

@davidss101
Copy link
Author

I'm sorry I forgot to mention that this is what I am looking for:

Screenshot 2024-02-29 at 4 36 10 PM

@davidss101
Copy link
Author

Hi Everyone,

Since I was ultimately interested in only the values in column1 which were "1", I used this code that I adapted from another website. Unfortunately, I forget now what that site was.

df2 <- df1 %>% group_by(column1) %>% mutate(sequence = data.table::rleid(column2 == 1),) %>% filter(column2 == 1) %>% group_by(column1, sequence) %>% summarise(length = n())

Thanks.

@williamlai2
Copy link

Hi, the issues here a specific to the package code.

You might get more help on your problem at: https://community.rstudio.com/

@psychelzh
Copy link

Or a better place to go is https://stackoverflow.com/.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants