拆分字符串并返回唯一值

时间:2017-04-18 00:52:35

标签: r string unique strsplit

我有一个像这样的字符串列表:

D<-c("0,0,0,0,0,0,0", "0,0,0,0,0,0,0,", "0,20,0,0,0,30,0", "0,60,61,70,0,0,","0,1,1,0,0,0,0,")

我想最终得到一个精简版本,只有每个字符串的唯一值。

D2<-c("0","0","0,20,30","0,60,61,70","0,1")

我尝试使用strsplit和unique的组合循环,但最终得到了一堆NA。

3 个答案:

答案 0 :(得分:2)

这个问题已经吸引了三个答案,但即将被关闭。 his comment中thelatemail提供的最佳解决方案将缺失:

sapply(strsplit(D, ","), function(x) paste(unique(x), collapse = ","))
#[1] "0"          "0"          "0,20,30"    "0,60,61,70" "0,1" 

数据

由OP给出:

D < -c("0,0,0,0,0,0,0", "0,0,0,0,0,0,0,", "0,20,0,0,0,30,0", "0,60,61,70,0,0,","0,1,1,0,0,0,0,")

基准

小基准

library(stringr)
microbenchmark::microbenchmark(
  thelatemail = sapply(strsplit(D, ","), function(x) paste(unique(x), collapse = ",")),
  epi99 = D %>% sapply(str_split, ",")  %>% sapply(unique) %>% sapply(paste, collapse=","),
  trungnt37 = {
    out <- c()
    for(i in 1:length(D)){
      k <- strsplit(x = D[i], split = ",")
      m <- paste(unique(unlist(k)), collapse = ",")
      out <- c(out, m)
    }
    out
  }
)

显示 thelatemail 的答案最快:

#Unit: microseconds
#        expr     min       lq      mean   median      uq     max neval
# thelatemail  57.770  61.9240  72.63590  67.9655  75.705 151.789   100
#       epi99 318.679 338.5020 383.76284 362.6670 410.054 781.972   100
#   trungnt37  74.384  81.3695  96.77465  87.7885 102.702 240.897   100

请注意epi99's stringr approach不会返回预期结果,因为它有逗号逗号。

答案 1 :(得分:0)

您应该使用strsplit和unlist函数。请尝试按照代码

out <- c()

for(i in 1:length(d)){
    k <- strsplit(x = d[i], split = ",")
    m <- paste(unique(unlist(k)), collapse = ",")
    out <- c(out, m)
}

答案 2 :(得分:-1)

使用在stringr和其他包中定义的管道运算符%&gt;%

library(stringr)
D<-c("0,0,0,0,0,0,0", "0,0,0,0,0,0,0,", "0,20,0,0,0,30,0", "0,60,61,70,0,0,","0,1,1,0,0,0,0,")
result <-  D %>% sapply(strsplit, ",")  %>% sapply(unique) %>% sapply(paste, collapse=",") 

D2<-c("0","0","0,20,30","0,60,61,70","0,1")
all(D2 == result)

# [1] TRUE