简体   繁体   中英

R: Create a new column based on a pattern in another column

I have a DF with several column. one of them contain the ID of the participant. Another contain one of the variable (V1), which for each participant, will have 36 successive rows containing "3", 36 successive rows containing "4" and 36 successive rows containing "5". However, sometimes the global pattern (for one participant) is 3, 4 and then 5 (as previously exposed) but sometimes (for other participants) it is 354 or 435 or 453 or 534 or 543. I would like to have a new column (V2) indicating this pattern for each participant. Would it be possible? If yes, could you please help me to do so? Cheers,

Adeline

ID V1 V2
A 3 345
A 3 345
... ... ...
A 4 345
A 4 345
... ... ...
A 5 345
A 5 345
... ... ...
B 5 543
... ... ...

You can try the code below:

library(dplyr)
DF |>
    group_by(ID) |>
    mutate(V2 = paste(unique(V1), collapse = ""))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM