I have list v:
v <- list(c("12", "1"), c("12", "2"), c("12", "3"), c("13", "1"), c("22", "3"), c("30", "4"))
and I need to merge the lines of this list which share the same first number by joining the second numbers separated by a comma, such that the resulting list w is like this:
w <- list(c("12", "1,2,3"), c("13", "1"), c("22", "3"), c("30", "4"))
> vv <- do.call(rbind.data.frame, v)
> names(vv) <- c("v1", "v2")
> vv
v1 v2
1 12 1
2 12 2
3 12 3
4 13 1
5 22 3
6 30 4
> vvv <-vv %>%
+ group_by(v1) %>%
+ summarise(v3 = paste0(v2, collapse = ","))
> vvv
# A tibble: 4 x 2
v1 v3
<fct> <chr>
1 12 1,2,3
2 13 1
3 22 3
4 30 4
> w <- as.list(as.data.frame(t(vvv)))
> w
$V1
v1 v3
12 1,2,3
Levels: 1,2,3 12
$V2
v1 v3
13 1
Levels: 1 13
$V3
v1 v3
22 3
Levels: 22 3
$V4
v1 v3
30 4
Levels: 30 4
> w <- lapply(as.list(1:dim(vvv)[1]), function(x) as.character(vvv[x[1],]))
> w
[[1]]
[1] "1" "1,2,3"
[[2]]
[1] "2" "1"
[[3]]
[1] "3" "3"
[[4]]
[1] "4" "4"
> w <- base::lapply(as.list(1:dim(vvv)[1]), function(x) as.character(vvv[x[1],]))
> w
[[1]]
[1] "1" "1,2,3"
[[2]]
[1] "2" "1"
[[3]]
[1] "3" "3"
[[4]]
[1] "4" "4"