在r中选定行的合并(粘贴)数据时,如何防止最终数据中的重复元素重复

艾哈迈德

我想在R中合并data.frame的多行。

这是我的data.frame:

    df<-data.frame(col1 = c("color","color","color","day","day","year"),
                 col2=c("red","red","red",1,1,18),
                 col3=c("red","blue","blue",10,12,17),
                 col4=c("red","blue","green",13,13,12))

df

      col1 col2 col3  col4
    1 color  red  red   red
    2 color  red blue  blue
    3 color  red blue green
    4   day    1   10    13
    5   day    1   12    13
    6  year   18   17    12

我使用以下代码合并基于df $ col1的相同行:

    aggregate(df, by=list(df$col1),paste)

结果是:

  Group.1                col1          col2            col3
1   color color, color, color red, red, red red, blue, blue
2     day            day, day          1, 1          10, 12
3    year                year            18              17
              col4
1 red, blue, green
2           13, 13
3               12

但是我将如何合并同名行的元素以产生如下的data.frame:

   col1 col2      col3             col4
1 color  red red//blue red//blue//green
2   day    1    10//12               13
3  year   18        17               12

非常感谢你。

丹妮

数据:

df <- data.frame(
        col1 = c("color","color","color","day","day","year"),
        col2 = c("red","red","red",1,1,18),
        col3 = c("red","blue","blue",10,12,17),
        col4 = c("red","blue","green",13,13,12),
        stringsAsFactors = FALSE)

解:

aggregate(df[,-1], by=df["col1"], function(x) paste(unique(x), collapse="//"))

说明:

  1. 在期间使用collapse参数topaste()aggregate()每个单元格中返回一个字符串,并且
  2. 包裹xunique()以类似“1 // 1”避事

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章