【问题标题】:Concatenating strings in data.frame columns without duplication连接 data.frame 列中的字符串而不重复
【发布时间】:2014-05-09 07:57:35
【问题描述】:

我在 data.frame d 的字符向量中有两列

t1 <- c("vector, market", "phone34, fax", "material55, animal", "cave", "monday", "fast98")
t2 <- c("vector, market", "phone, fax", "summer, animal", "pan23", "monday", "fast98, ticket")

d <- data.frame(t1, t2, stringsAsFactors=FALSE)

d
                  t1             t2
1     vector, market vector, market
2       phone34, fax     phone, fax
3 material55, animal summer, animal
4               cave          pan23
5             monday         monday
6             fast98 fast98, ticket

我想将两列连接到单列 t3,没有任何重复。

单独使用 paste 会给我重复。

d$t3

> d
                  t1             t2                                 t3
1     vector, market vector, market     vector, market, vector, market
2       phone34, fax     phone, fax           phone34, fax, phone, fax
3 material55, animal summer, animal material55, animal, summer, animal
4               cave          pan23                        cave, pan23
5             monday         monday                     monday, monday
6             fast98 fast98, ticket             fast98, fast98, ticket

想要的结果是

                  t1             t2                                 t3
1     vector, market vector, market                     vector, market
2       phone34, fax     phone, fax                phone34, phone, fax
3 material55, animal summer, animal         material55, animal, summer
4               cave          pan23                        cave, pan23
5             monday         monday                             monday
6             fast98 fast98, ticket                     fast98, ticket

如何在R 中有效地做到这一点?有向量化的解决方案吗?

【问题讨论】:

    标签: r duplicates concatenation vectorization paste


    【解决方案1】:

    你需要strsplit每个向量的每个条目,对结果向量做一个union,然后paste它们一起:

    strsplit(d$t1, split=", ") -> t1s   ## list of vectors
    strsplit(d$t2, split=", ") -> t2s   ## list of vectors
    
    # do a union of the elements and paste them together to get a single string
    d$t3 <- sapply(1:length(t1), function(x) paste(union(t1s[[x]], t2s[[x]]), collapse=", "))
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2012-10-13
      • 2018-08-30
      • 2016-08-21
      • 2017-04-05
      • 2015-02-18
      • 2013-10-04
      • 1970-01-01
      • 2019-10-23
      • 2019-01-05
      相关资源
      最近更新 更多