18

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")
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
KillerSnail
  • 3,321
  • 11
  • 46
  • 64
  • 5
    I would suggest something like `gsub(".*_(.*)", "\\1", string_thing)` or `gsub(".*_", "", string_thing)` rather than splitting the string and then extracting the last piece.... – A5C1D2H2I1M1N2O1R2T1 Mar 22 '17 at 05:43
  • 3
    As already pointed, the splitting is unnecessary. You want to extract part of a string. You can use `str_extract` also. Try `str_extract(string_thing, "(?<=_)[^_]*$")`, that means: "extract everything different from an underscore that starts from an underscore and arrives to the end of the string". – nicola Mar 22 '17 at 06:09
  • 2
    Possible duplicate of [How to get last subelement of every element of a list in R](http://stackoverflow.com/questions/36143119/how-to-get-last-subelement-of-every-element-of-a-list-in-r) Or If you dont want to split the vector [Extracting text after last period in string in R](http://stackoverflow.com/questions/31774086/extracting-text-after-last-period-in-string-in-r) – Ronak Shah Mar 22 '17 at 06:14
  • This question could have its own answer. This is a specific example and there can be a specific answer to this particular example. The question is asking about strings, the answer attached to the question is for lists and does not provide a string example. This kind of string problem can be solved easily with stringr: word(string_thing[2], 4:5, sep = ("_")) result: "string" "thing". – Monduiz May 28 '17 at 12:01
  • 1
    Too late to answer now, but if anyone else does in fact want to _split_ the string using the final underscore, this should do it for you: `_(?=[^_]+$)` – Tom Wagstaff Nov 13 '20 at 13:57

2 Answers2

20

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" ""  
Hugh
  • 15,521
  • 12
  • 57
  • 100
16

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)
akrun
  • 874,273
  • 37
  • 540
  • 662