/ / Contraer columnas por variable de agrupación (en base) - r

Contraer columnas por variable de agrupación (en la base) - r

Tengo una variable de texto y una variable de agrupación. Me gustaría contraer la variable de texto en una cadena por fila (combinar) por factor. Mientras la columna del grupo diga m Quiero agrupar el texto juntos y así sucesivamente. Proporcioné un conjunto de datos de muestra antes y después. Estoy escribiendo esto para un paquete y hasta ahora he evitado toda dependencia en otros paquetes excepto en wordcloudy me gustaría mantenerlo de esta manera.

Sospecho rle puede ser útil con cumsum pero no he podido resolver esto.

Gracias de antemano.

Cómo se ven los datos

                                 text group
1       Computer is fun. Not too fun.     m
2               No its not, its dumb.     m
3              How can we be certain?     f
4                    There is no way.     m
5                     I distrust you.     m
6         What are you talking about?     f
7       Shall we move on?  Good then.     f
8 Im hungry.  Lets eat.  You already?     m

Cómo me gustaría que se vieran los datos

                                                       text group
1       Computer is fun. Not too fun. No its not, its dumb.     m
2                                    How can we be certain?     f
3                          There is no way. I distrust you.     m
4 What are you talking about? Shall we move on?  Good then.     f
5                       Im hungry.  Lets eat.  You already?     m

Los datos

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")

EDITAR: Descubrí que puedo agregar una columna única para cada ejecución de la variable de grupo con:

x <- rle(as.character(dat$group))[[1]]
dat$new <- as.factor(rep(1:length(x), x))

Flexible:

                                 text group new
1       Computer is fun. Not too fun.     m   1
2               No its not, its dumb.     m   1
3              How can we be certain?     f   2
4                    There is no way.     m   3
5                     I distrust you.     m   3
6         What are you talking about?     f   4
7       Shall we move on?  Good then.     f   4
8 Im hungry.  Lets eat.  You already?     m   5

Respuestas

5 para la respuesta № 1

Esto hace uso de rle para crear una identificación para agrupar las oraciones. Utiliza tapply junto con paste para juntar la salida

## 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])

1 para la respuesta № 2

Obtuve la respuesta y volví para publicar, pero Dason me dio una respuesta y más comprensible que la mía.

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)

EDITAR Cómo lo hice con el agregado y lo que aprendí de su respuesta (aunque tapply es una mejor solución):

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]])