正则表达式 – R列表字符删除

前端之家收集整理的这篇文章主要介绍了正则表达式 – R列表字符删除前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
lst1是一个列表:

lst1 <- list(c("all the apples","apples in the tables","fashion prosthetics"),c("meteorological concepts","effects of climate change","environmental"))

我想保留列表结构并从所有单词中删除最后一个.所需答案如下:

> lst1
[[1]]
[1] "all the apple"      "apple in the table" "nature"            

[[2]]
[1] "meteorological concept"   "effect of climate change"
[3] "environmental"

我试过了

gsub("\\'s|s$|s[[:space:]]{0}","",lst1)

但它不保留列表结构.

怎么做到呢?

解决方法

您可以使用带有lapply的gsub循环遍历列表元素

lapply(lst1,gsub,pattern= "\\'s|s$|s\\b",replacement='')
#[[1]]
#[1] "all the apple"       "apple  in the table" "fashion prosthetic" 

#[[2]]
#[1] "meteorological concept"    "effect  of climate change"
#[3] "environmental"

猜你在找的正则表达式相关文章