String split with conditions in R

后端 未结 7 1354
一向
一向 2021-02-04 00:05

I have this mystring with the delimiter _. The condition here is if there are two or more delimiters, I want to split at the second delimiter and if th

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-04 01:04

    A little longer, but needs less regular expression knowledge:

    library(stringr)
    indx <- str_locate_all(mystring, "_")
    
    for (i in seq_along(indx)) {
      if (nrow(indx[[i]]) == 1) {
        mystring[i] <- strsplit(mystring[i], ".ReCal")[[1]][1]
      } else {
        mystring[i] <- substr(mystring[i], start = 1, stop = indx[[i]][2] - 1)
      }
    }
    

提交回复
热议问题