在 R 中将字符向量分解为单个单词



我有一个这样的字符向量(vec):

[1] "super good dental associates"   "cheap dentist in bel air md"    
    "dentures   "                    "dentures   "                    
    "in office teeth whitening"      "in office teeth whitening"      
    "dental gum surgery bel air, md"
[8] "dental implants"                "dental implants"                
    "veneer teeth pictures"

我需要把它分解成个人的话。 我试过这个:

singleWords <- strsplit(vec, ' ')[[1]]

但是,我只得到该向量的第一个元素的拆分:

[1] "super"      "good"       "dental"     "associates"

如何将所有单词作为单个元素的单个向量获取?

你可以试试:

strsplit(paste(vec, collapse = " "), ' ')[[1]]

只是为了确认我的评论,既然你提到它不起作用,看看。 由于有几个元素有额外的空格,我建议使用 \s+ 作为正则表达式进行拆分,而不是我评论中的单空格。 干杯。

> ( newVec <- unlist(sapply(vec, strsplit, "\s+", USE.NAMES = FALSE)) )
# [1] "super"      "good"       "dental"     "associates" "cheap"      "dentist"   
# [7] "in"         "bel"        "air"        "md"         "dentures"   "dentures"  
#[13] "in"         "office"     "teeth"      "whitening"  "in"         "office"    
#[19] "teeth"      "whitening"  "dental"     "gum"        "surgery"    "bel"       
#[25] "air,"       "md"         "dental"     "implants"   "dental"     "implants"  
#[31] "veneer"     "teeth"      "pictures" 

而且由于我在那里看到一个杂散的逗号,因此最好通过调用gsub来清理所有标点符号(如果有的话)

> gsub("[[:punct:]]", "", newVec)

最新更新