How do I add a list box to a data frame in R?

I have 2 tables as shown below:

a = read.table(text=' a b
1 c
1 d
2 c
2 a
2 b
3 a
', head=T)



b = read.table(text=' a c
1 x i
2 y j 
3 z k
', head=T)

      

And I want the result to be like this:

1 x i c d
2 y j c a b
3 z k a

      

I originally thought to use tapply to convert them to lists (eg aa = tapply (a [, 2], a [, 1], function (x) paste (x, collapse = ","))) then add it back to table b, but I'm stuck ...

Any suggestion to do this? Thanks a million.

+3


source to share


1 answer


One way to do it:



mapply(FUN = c, 
       lapply(split(b, row.names(b)), function(x) as.character(unlist(x, use.names = FALSE))), 
       split(as.character(a$b), a$a), 
       SIMPLIFY = FALSE)
# $`1`
# [1] "x" "i" "c" "d"
# 
# $`2`
# [1] "y" "j" "c" "a" "b"
# 
# $`3`
# [1] "z" "k" "a"

      

+1


source







All Articles