Collapse columns by grouping variable (in base)

后端 未结 2 1403
爱一瞬间的悲伤
爱一瞬间的悲伤 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]])
    
    0 讨论(0)
  • 2021-01-20 20:12

    This makes use of rle to create an id to group the sentences on. It uses tapply along with paste to bring the output together

    ## Your example data
    dat <- structure(list(text = c("Computer is fun. Not too fun.", "No its not, its dumb.", 
    "How can we be certain?", "There is no way.", "I distrust you.", 
    "What are you talking about?", "Shall we move on?  Good then.", 
    "Im hungry.  Lets eat.  You already?"), group = structure(c(2L, 
    2L, 1L, 2L, 2L, 1L, 1L, 2L), .Label = c("f", "m"), class = "factor")), .Names = c("text", 
    "group"), row.names = c(NA, 8L), class = "data.frame")
    
    
    # Needed for later
    k <- rle(as.numeric(dat$group))
    # Create a grouping vector
    id <- rep(seq_along(k$len), k$len)
    # Combine the text in the desired manner
    out <- tapply(dat$text, id, paste, collapse = " ")
    # Bring it together into a data frame
    answer <- data.frame(text = out, group = levels(dat$group)[k$val])
    
    0 讨论(0)
提交回复
热议问题