2

I have a set of data in the form of strings. They are text responses given to a question, and some people gave multiple responses to the question. I want to combine each individual's text responses, i.e. aggregate by individual.

However, when I aggregate(), even using paste, paste0, or str_c (from stringr package), I get essentially a list of lists.

I cannot turn this into a dataframe to write to csv, I cannot seem to flatten these by unlisting without going by each individual cell which is prohibitive as I have over 300 responses.

Is there a way I can aggregate that will combine each person's response into a single string? Or an easy way to flatten them out so that I can do so?

Response <- c("A","B","A","A","B","C","A","B")
df<-cbind(Person,Response)
df<-aggregate(Response~Person,data=df,paste0)```

I have:

Person      Response
1             "A"
1             "B"
2             "A"
3             "A"
3             "B"
3             "C"
4             "A"
4             "B"

I want to get to:

Person        Response
1               "AB"   
2               "A"
3               "ABC"
4               "AB"

What I'm getting instead is:

Person     Response
1           c("A","B")
2           "A"
3           c("A","B","C")
4           c("A","B")


Thanks.
Jessica
  • 23
  • 4

1 Answers1

1

We can change the paste0 to paste with collapse = ""

aggregate(Response ~ Person, data = df, FUN = paste, collapse="")
#  Person Response
#1      1       AB
#2      2        A
#3      3      ABC
#4      4       AB

Here, paste0 is not doing anything, and resulting in a list column instead of a concatenated string, e..g

paste0(c("A", "B", "C")) # returns the same vector
#[1] "A" "B" "C"

paste(c("A", "B", "C"), collapse="")
#[1] "ABC"

whereas paste0 works, when two vectors are concatenated

paste0("A", "B")
#[1] "AB"

data

df <- structure(list(Person = c(1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L), Response = c("A", 
 "B", "A", "A", "B", "C", "A", "B")), class = "data.frame", 
 row.names = c(NA, -8L))
akrun
  • 874,273
  • 37
  • 540
  • 662