R删除每个单词末尾的s

R remove s at the end of each word

我有以下 R 代码:

temp <- strsplit(unlist(test_data$`Product Description`), split=" ")
temp <- lapply(temp, function(x) gsub("s$", '', x))

我想做的是去掉 'Product Description' 列中每个单词末尾的 s。

代码的第一步工作完美,它通过为每个描述创建一个单词列表来拆分数据。

但是,第二步不行。它不会删除 's'

sub 与模式 (.*)s$ 结合使用,然后替换为第一个捕获组。

temp <- lapply(temp, function(x) sub("(.*)s$", '\1', x))

这里的想法是,如果模式确实匹配,我们将替换为最终的 s 剥离。如果模式不匹配,那么 sub 将只是 return 整个未触及的字符串。

Demo