R:将行内容组合为相同的模式

时间:2017-11-20 07:52:36

标签: r dataframe

我有一个很大的数据框架。

我希望将具有相同类型模式的行内容组合在一起,并使用“/”符号分隔内容。

例如:

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

我想将df转移到:

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 个答案:

答案 0 :(得分:4)

这个例子应该有所帮助:

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

我建议您将列名更改为与function不同的名称,以避免与function命令发生任何不必要的冲突。

答案 1 :(得分: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)

这应该可以解决问题:

    df %>% dplyr::select(x, y) %>% 
dplyr::group_by(x) %>%  
dplyr::summarise(y=y %>% 
paste(collapse = " / ")) -> df_transfer