Search code examples
rconcatenationstrsplit

split string and concatenating to remove a portion of string


I am trying to remove a portion of a string. The best I can come up with is to strsplit and then concatenate (maybe there is an easier way.

list<-as.character(c("joe_joe_ID1000", "bob_bob_ID20000"))
list<-strsplit(list, "_")

I would like my output to be "joe joe" and "bob bob" but I am unclear on how to concatenate the resulting strsplit list. And perhaps there is an even easier way Thanks.


Solution

  • Using sapply() and paste() you can do this:

    sapply(list, function(x) paste(x[1:2], collapse = " "))
    [1] "joe joe" "bob bob"
    

    Or something more akin to akrun's solution but slightly different:

    c("joe_joe_ID1000", "bob_bob_ID20000") %>% 
      sub("[^_]*$", " ", .) %>%
      gsub("_", " ", ., fixed = TRUE) %>%
      trimws()
    [1] "joe joe" "bob bob"
    

    Original data:

    list<-as.character(c("joe_joe_ID1000", "bob_bob_ID20000"))
    list<-strsplit(list, "_")