1

I have a dataframe like the following:

1   a
2   a
3   a
4   a
a   a
x   b
y   b
b   b

How can I use are to get something like:

a   1,2,3,4
b   x,y

Consider that the identifier a and b are also listed in column 1 but should not be part of the concatenated string. Many thanks!

1
  • Hi Henry, my new question is an extension of the question you are linking to. Commented Mar 30, 2015 at 15:09

1 Answer 1

1

Based on the initial description,

aggregate(V1~V2, df1, toString)
#  V2         V1
#1  a 1, 2, 3, 4
#2  b       x, y

Update

Suppose, if we need to remove the elements in first column ('V1') that are also present in the grouping column ('V2') before we paste the elements of V1 together, a couple of options are listed below:

library(data.table)
setDT(df2)[!V1 %chin% V2, toString(V1), by=V2]
#    V2         V1
#1:  a 1, 2, 3, 4
#2:  b       x, y

Or

 library(dplyr)   
 df2 %>%
     filter(!V1 %in% V2) %>% 
     group_by(V2) %>%
     summarise(V1=toString(V1))

data

df1 <- structure(list(V1 = c("1", "2", "3", "4", "x", "y"),
 V2 = c("a", 
 "a", "a", "a", "b", "b")), .Names = c("V1", "V2"), 
class = "data.frame", row.names = c(NA, -6L))

df2 <- structure(list(V1 = c("1", "2", "3", "4", "a", "x", "y", "b"), 
 V2 = c("a", "a", "a", "a", "a", "b", "b", "b")), .Names = c("V1", 
"V2"), class = "data.frame", row.names = c(NA, -8L))
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you akrun. I just edit my question slightly. Do you also know a solution for the more advanced problem? Thank you!
@Arun Thanks, I thought %chin% was new.
@Arun I guess I could remove the filter option and put that in the summarise. I was thinking this would be a bit more clear for the OP.
Thank you very much akrun! that worked like a charme! very much helped me to finish my work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.