R get the last element from str_split

I have a list of R strings and I want to get the last element of each

require(stringr)

string_thing <- "I_AM_STRING"
Split <- str_split(string_thing, "_")
Split[[1]][length(Split[[1]])]

      

but how to do this with a list of strings?

require(stringr)

string_thing <- c("I_AM_STRING", "I_AM_ALSO_STRING_THING")
Split <- str_split(string_thing, "_")

#desired result
answer <- c("STRING", "THING")

      

thank

+3


source to share


2 answers


We can go through list

with sapply

and get the number "n" of the last items withtail

sapply(Split, tail, 1)
#[1] "STRING" "STRING"

      



If there is only one string, use [[

to convert list

to vector

and get the last element withtail

tail(Split[[1]], 1)

      

+3


source


As the comment on your question says, this is fine for gsub

:

gsub("^.*_", "", string_thing)

      



I would recommend that you also pay attention to the following cases.

string_thing <- c("I_AM_STRING", "I_AM_ALSO_STRING_THING", "AM I ONE", "STRING_")
gsub("^.*_", "", string_thing)
[1] "STRING"   "THING"    "AM I ONE" ""  

      

+2


source







All Articles