Set collapse for paste function in aggregate

Viewed 388

I want to aggregate a data.frame with two columns: in one column I have "num", which is an identifier number and in the other I have text. It is important that the aggregated text has a space between the individual parts. My code is this:

data_aggr <- aggregate(
  x = data_aggr,
  FUN = paste,
  by = list(data_aggr$num)
)

I have tried the obvious with FUN = paste(collapse = " ") and

FUN = paste,
collapse = " ",

but that doesn't work. How do I need to do this?

2 Answers

Aggregate can be used to paste together the rows with the same value of num as follows:

data_aggr <- data.frame(num=c(1,1,1,2,2), letters=letters[1:5])
aggregate(data_aggr$letters, list(data_aggr$num), FUN=paste, collapse= " ")

#   Group.1     x
# 1       1 a b c
# 2       2   d e

A dplyr solution, the idea is to create a new column with row number to be able to conduct the operation on each row.

> library(dplyr)
> df.ask <- data.frame('Num' = 1:10, 
+                      'Text' = letters[1:10])
> 
> df.ask %>% 
+   mutate(row_num = row_number()) %>% 
+   group_by(row_num) %>% 
+   mutate(together = paste(Num, Text, collapse = ' ')) %>%
+   ungroup() %>% 
+   select(-row_num)
# A tibble: 10 x 3
     Num Text  together
   <int> <fct> <chr>   
 1     1 a     1 a     
 2     2 b     2 b     
 3     3 c     3 c     
 4     4 d     4 d     
 5     5 e     5 e     
 6     6 f     6 f     
 7     7 g     7 g     
 8     8 h     8 h     
 9     9 i     9 i     
10    10 j     10 j 
Related