Reputation: 2425
I have the data set:
df <- data.frame(g = c("X", "X", "Y", "Z", "Y", "Z", "Z"),
r = c("A", "B", "C", "C", "A", "A", "A"))
And I would to manipulate the data in a way that I get the result:
g | r
X | A B
Y | A C
Z | A C
So for each g all the unique r values are listed. I can use the reshape package for this. But I would like to be able to do this with standard R, because the script will be shared with people with a very limited knowledge of R.
Upvotes: 3
Views: 596
Reputation: 60000
How about aggregate()
?
aggregate( df$r , by = list( df$g ) , function(x) paste0( sort( unique(x) ) , collapse = "" ) )
# Group.1 x
#1 X AB
#2 Y AC
#3 Z AC
Upvotes: 2
Reputation: 6584
Give this a try:
dg <- data.frame(
g = levels(df$g),
r = tapply(df$r, df$g, function(n) {paste(sort(unique(n)), collapse = " ")})
)
> dg
g r
X X A B
Y Y A C
Z Z A C
Upvotes: 1