String split with conditions in R

后端 未结 7 1351
一向
一向 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 00:43

    gregexpr can search for a pattern in strings and give the location.

    First, we use gregexpr to find the location of all _ in each element of mystring. Then, we loop through that output and extract the index of second _ within each element of mystring. If there is no second _, it'll return an NA (check inds in the example below).

    After that, we can either extract the relevant part using substr based on the extracted index or, if there is NA, we can split the string at .ReCal and keep only the first part.

    inds = sapply(gregexpr("_", mystring, fixed = TRUE), function(x) x[2])
    ifelse(!is.na(inds),
           substr(mystring, 1, inds - 1), 
           sapply(strsplit(mystring, ".ReCal"), '[', 1))
    #[1] "MODY_60.2"   "MODY_116.21" "MODY_116.3"  "MODY_116.4" 
    

提交回复
热议问题