Q:

Country / Year Table from Panel Data

I have panel data that looks something like this:
df<-data.frame(a=c("A","A","A","B","B","C","C","C","C"),b=c("1","2","3","4","5","1","2","3","5"),var=c(1,1,1,NA,1,NA,1,1,1))
df
  a b var
1 A 1   1
2 A 2   1
3 A 3   1
4 B 4  NA
5 B 5   1
6 C 1  NA
7 C 2   1
8 C 3   1
9 C 5   1

What I want to do might seem simple, however, I have not been able to accomplish it so far. I'd like R to make a table (ideally already in LaTeX-code using xtable or other suitable packages) that gives me for every value in column a every value in column b where column c is not NA. Hence, in the end the result should look like this:
A 1,2,3
B 5
C 2,3,5

I have tried to play around with table() but was not able to come up with something that makes the whole thing easier.
Thank you!

A:

Here is an option using dplyr, filter out the rows having NA elements in 'var', grouped by 'a', paste the unique elements in 'b'
library(dplyr)
df %>% 
   filter(!is.na(var)) %>% 
   group_by(a) %>%
   summarise(b = toString(unique(b)))

Or with aggregate from base R
aggregate(b ~a, df[!is.na(df$var),], FUN = function(x) toString(unique(x)))
#  a       b
#1 A 1, 2, 3
#2 B       5
#3 C 2, 3, 5

