Delete list character R

lst1 is a list:

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

I want to keep the list structure and remove the last s from all words. The desired answer is given below:

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

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

I tried

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

but it does not preserve the list structure.

How can I do that?

+4
source share
3 answers

You can use gsubc lapplyto cycle through list items

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"    
+3
source

The same solution, another regex using a group that does not contain a capture to leave the space as is:

> 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"           
+1
source

Simplified regex:

lapply(lst1, function(x) gsub('s\\b', '', x))

Results in:

[[1]]
[1] "all the apple"      "apple in the table" "fashion prosthetic"

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

All Articles