There are many ways to skin a cat in R, here is a Base, tidyverse, and data.table way:
# Base R solution: res => data.frame
res <- aggregate(
LOC ~ ID,
df,
FUN = function(x){
paste0(unique(x), collapse = ' + ')
}
)
# Output data.frame to console: data.frame => stdout(console)
res
# Tidyverse method: tv_res => tibble
library(tidyverse)
tv_res <- df %>%
group_by(ID) %>%
distinct() %>%
summarise(LOC = str_c(LOC, collapse = ' + ')) %>%
ungroup()
# Print the data.frame to the console:
# tibble => stdout(console)
tv_res
# Data.table method:
# Coerce data.frame to data.table: dt => data.table object
dt <- data.table(df)
# Aggregate the data.table: dt_res => data.table object
dt_res <- dt[,
list(LOC = paste(unique(LOC), collapse = ' + ')),
by = ID]
# Print the data to the console: data.table => console(stdout)
dt_res
Data used:
# Import the data: df => data.frame
df <- structure(list(ID = c(1L, 1L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L),
LOC = c("A", "A", "A", "B", "A", "A", "A", "A", "B", "C")),
class = "data.frame", row.names = c(NA, -10L))