This question already has an answer here:
这个问题在这里已有答案:
- Aggregating by unique identifier and concatenating related values into a string [duplicate] 4 answers
通过唯一标识符聚合并将相关值连接成字符串[duplicate] 4个答案
I have a big data frame.
我有一个很大的数据框架。
I want to combine row content which with same type pattern, and use "/" symbol separate contents.
我想组合具有相同类型模式的行内容,并使用“/”符号单独的内容。
For example:
df>
type function
A cleaning
A improve chemical reaction
A reduce scratch
B improve planarization
B improve slurry distribution
C cleaning
C improve slurry distribution
D reduce scratch
I want df transfer to:
我想转发到:
df_transfer>
type function
A cleaning/improve chemical reaction/reduce scratch
B improve planarization/improve slurry distribution
C cleaning/improve slurry distribution
D reduce scratch
2 个解决方案
#1
4
This example should help:
这个例子应该有帮助:
df = data.frame(type = c("A","A","A","B","B"),
fun = c("cleaning", "improve chemical reaction", "reduce scratch",
"improve planarization", "improve slurry distribution"),
stringsAsFactors = F)
library(dplyr)
df %>%
group_by(type) %>%
summarise(fun = paste0(fun, collapse = "/"))
# # A tibble: 2 x 2
# type fun
# <chr> <chr>
# 1 A cleaning/improve chemical reaction/reduce scratch
# 2 B improve planarization/improve slurry distribution
I'd suggest you change your column name to something different than function
to avoid any unnecessary conflicts with the function
command.
我建议您将列名更改为与函数不同的名称,以避免与函数命令发生任何不必要的冲突。
#2
0
x <- c("A","A","A","B","B","C","C","D")
y <- c("cleaning","improve chemical reaction"," reduce scratch"," improve planarization","improve slurry distribution"," cleaning"," improve slurry distribution","reduce scratch")
df <- data.frame(x,y)
this should do the trick:
这应该是诀窍:
df %>% dplyr::select(x, y) %>%
dplyr::group_by(x) %>%
dplyr::summarise(y=y %>%
paste(collapse = " / ")) -> df_transfer
#1
4
This example should help:
这个例子应该有帮助:
df = data.frame(type = c("A","A","A","B","B"),
fun = c("cleaning", "improve chemical reaction", "reduce scratch",
"improve planarization", "improve slurry distribution"),
stringsAsFactors = F)
library(dplyr)
df %>%
group_by(type) %>%
summarise(fun = paste0(fun, collapse = "/"))
# # A tibble: 2 x 2
# type fun
# <chr> <chr>
# 1 A cleaning/improve chemical reaction/reduce scratch
# 2 B improve planarization/improve slurry distribution
I'd suggest you change your column name to something different than function
to avoid any unnecessary conflicts with the function
command.
我建议您将列名更改为与函数不同的名称,以避免与函数命令发生任何不必要的冲突。
#2
0
x <- c("A","A","A","B","B","C","C","D")
y <- c("cleaning","improve chemical reaction"," reduce scratch"," improve planarization","improve slurry distribution"," cleaning"," improve slurry distribution","reduce scratch")
df <- data.frame(x,y)
this should do the trick:
这应该是诀窍:
df %>% dplyr::select(x, y) %>%
dplyr::group_by(x) %>%
dplyr::summarise(y=y %>%
paste(collapse = " / ")) -> df_transfer