我有一组字符串形式的数据。它们是对一个问题的文字回复,有些人对该问题有多个回复。我想合并每个人的文字回复,即按个人汇总。
但是,当我进行汇总()时,即使使用粘贴,paste0或str_c(来自stringer包),也实际上获得了列表列表。
我无法将其转换为要写入csv的数据帧,我似乎无法通过取消列出来扁平化这些内容,而不用逐个访问每个单元格,因为我拥有300多个响应,因此这是禁止的。
有没有一种我可以汇总的方法,可以将每个人的回答组合成一个字符串?还是将它们弄平以便我可以这样做的简单方法?
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.
答案 0 :(得分:1)
我们可以使用paste0
将paste
更改为collapse = ""
aggregate(Response ~ Person, data = df, FUN = paste, collapse="")
# Person Response
#1 1 AB
#2 2 A
#3 3 ABC
#4 4 AB
此处paste0
没有执行任何操作,并导致了list
列而不是连接字符串,例如
paste0(c("A", "B", "C")) # returns the same vector
#[1] "A" "B" "C"
paste(c("A", "B", "C"), collapse="")
#[1] "ABC"
paste0
有效,但两个向量是串联的
paste0("A", "B")
#[1] "AB"
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))