R:访问列表中每个元素的最后一个子元素

R: Access the last subelement of each element in a list

假设我有一个字符向量,例如:

 x <- c('A__B__Mike','A__Paul','Daniel','A__B__C__Martha','A__John','A__B__C__D__Laura')

我想要一个仅包含最后位置名称的向量;我想我可以使用正则表达式删除第一个块,但是说我想使用 strsplit() 按 '__':

分割
 x.list <- strsplit(x, '__')

如何访问此列表中每个元素的最后一个子元素(名称)?知道位置才知道怎么做:

 sapply(x.list, "[[", 1)

但是position可变的时候如何访问last呢?谢谢!

无论如何,首先从 x 中提取名称的最快方法是什么?有比 strsplit 方法更快的方法吗?

我们可以用 base R 做到这一点。使用 sub

sub(".*__", "", x)
#[1] "Mike"   "Paul"   "Daniel" "Martha" "John"   "Laura" 

strsplit,我们用tail

得到最后一个元素
sapply(strsplit(x, '__'), tail, 1)
#[1] "Mike"   "Paul"   "Daniel" "Martha" "John"   "Laura" 

或者找到位置,我们可以使用gregexpr然后使用substring

提取
substring(x, sapply(gregexpr("[^__]+", x), tail, 1))
#[1] "Mike"   "Paul"   "Daniel" "Martha" "John"   "Laura" 

或者用stri_extract_last

library(stringi)
stri_extract_last(x, regex="[^__]+")
#[1] "Mike"   "Paul"   "Daniel" "Martha" "John"   "Laura" 

使用stringr

word功能
library(stringr)
word(x,start = -1,sep = "\_+")