Collapse columns by grouping variable (in base)

后端 未结 2 1426
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-20 19:42

I have a text variable and a grouping variable. I\'d like to collapse the text variable into one string per row (combine) by factor. So as long as the group column says

2条回答
  •  無奈伤痛
    2021-01-20 20:00

    I got the answer and came back to post but Dason beat me to it and more understandably than my own.

    x <- rle(as.character(dat$group))[[1]]
    dat$new <- as.factor(rep(1:length(x), x))
    
    Paste <- function(x) paste(x, collapse=" ")
    aggregate(text~new, dat, Paste)
    

    EDIT How I'd do it with aggregate and what I learned from your response (though tapply is a better solution):

    y <- rle(as.character(dat$group))
    x <- y[[1]]
    dat$new <- as.factor(rep(1:length(x), x))
    
    text <- aggregate(text~new, dat, paste, collapse = " ")[, 2]
    data.frame(text, group = y[[2]])
    

提交回复
热议问题