Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R get last element from str_split [duplicate]

Tags:

regex

r

stringr

I have a R list of 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 can I 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")

Thanks

like image 528
KillerSnail Avatar asked Mar 22 '17 05:03

KillerSnail


2 Answers

As the comment on your question suggests, this is suitable for gsub:

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

I'd recommend you take note of the following cases as well.

string_thing <- c("I_AM_STRING", "I_AM_ALSO_STRING_THING", "AM I ONE", "STRING_")
gsub("^.*_", "", string_thing)
[1] "STRING"   "THING"    "AM I ONE" ""  
like image 120
Hugh Avatar answered Nov 18 '22 15:11

Hugh


We can loop through the list with sapply and get the 'n' number of last elements with tail

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

If there is only a single string, then do use [[ to convert list to vector and get the last element with tail

tail(Split[[1]], 1)
like image 23
akrun Avatar answered Nov 18 '22 16:11

akrun