2017-02-20 29 views
0

我的示例數據集如下所示。我需要計算字符的數量。計算字符串中的字符數R

keyword <- c("advertising", 
     "advertising budget", 
     "marketing plan detail", 
     "marketing budget and forecast") 

我試過了「nchar」函數,但它實際上計算的是位數。對於這個樣本,結果應該是1,2,3,4。

+3

也許你想計算單詞的數量,而不是字符的數量。無論如何 - 'nchar'不會計算數字的位數。您的示例不包含數字。 –

+1

'stringi :: stri_count_words(關鍵字)' –

回答

1

一種選擇是str_count和字指定模式(\\w+

library(stringr) 
str_count(keyword, "\\w+") 
#[1] 1 2 3 4 

或用base R

lengths(gregexpr("\\w+", keyword)) 
#[1] 1 2 3 4 
1
unlist(lapply(strsplit(keyword, split = "\ "), length)) 
[1] 1 2 3 4