提取R中字符串中的最后一个单词-面对错误

问题描述 投票:0回答:1

[首先,我希望将Description列的最后一个单词和第一个单词(此列包含至少3个单词)提取到新创建的列firstwordlastword中。但是,word()函数并不适用于所有行。因此,有很多行的lastword为空,尽管这些行实际上是最后一个字(如Description列所示)。这在前两行代码中显示。

[第二,如果lastword为空,我也试图获取第三行代码以firstword替换lastword。但是它不起作用。

是否有纠正方法?

c1$lastword = word(c1$Description,start=-1) #extract last word
c1$firstword = word(c1$Description,start=1) #extract first word
c1$lastword=ifelse(c1$lastword == " ", c1$firstword, c1$lastword)

Screenshot of dataset - lastword still has missing values

string extract word
1个回答
0
投票

[我意识到Description变量的某些行的开头有空白,在R中查看时未显示。

使用stri_trim()删除空白解决了该问题。

[c1$Description = stri_trim(c1$Description, "left")#删除空格

© www.soinside.com 2019 - 2024. All rights reserved.