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)
但它没有保留列表结构。
怎么做?
答案 0 :(得分:3)
您可以gsub
与lapply
一起使用循环列表元素
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"
答案 1 :(得分:1)
相同的解决方案,不同的正则表达式,使用非捕获组按原样保留空格:
> lapply(lst1, gsub, pattern="s(?= |$)", replacement="", perl=TRUE)
[[1]]
[1] "all the apple" "apple in the table" "fashion prosthetic"
[[2]]
[1] "meteorological concept" "effect of climate change" "environmental"
答案 2 :(得分:1)
更简单的正则表达式:
lapply(lst1, function(x) gsub('s\\b', '', x))
结果:
[[1]]
[1] "all the apple" "apple in the table" "fashion prosthetic"
[[2]]
[1] "meteorological concept" "effect of climate change"
[3] "environmental"