Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the number of words in a text (string)?

I have this string vector (for example):

str <- c("this is a string current trey",
    "feather rtttt",
    "tusla",
    "laq")

To count the number of words in this vector I used this (as given here Count the number of words in a string in R?, which is a possible duplicate but with another issue)

No_words <- sapply(gregexpr("\\W+", str), length) + 1

but it returns

6 2 2 2

String has only 1 element in last two places (i.e. "tusla" and "laq")

so it should return

6 2 1 1

How do I get around this problem?

like image 726
user3664020 Avatar asked May 22 '14 08:05

user3664020


3 Answers

Use the stringi package and stri_count:

require(stringi)
str <- c(
"this is a string current trey",
"nospaces",
"multiple    spaces",
"   leadingspaces",
"trailingspaces    ",
"    leading and trailing    ",
"just one space each")

> stri_count(str,regex="\\S+")
[1] 6 1 2 1 1 3 4
like image 123
Spacedman Avatar answered Nov 10 '22 22:11

Spacedman


Use the wc-function from the qdap package.

str <- c("this is a string current trey", 
         "feather rtttt", 
         "tusla", 
         "laq")

library("qdap")

wc(str)

That returns:

wc(str)

[1] 6 2 1 1
like image 20
Sdae Avatar answered Nov 10 '22 22:11

Sdae


You can try

sapply(gregexpr("\\S+", x), length)
## [1] 6 2 1 1

Or as suggested in comments you can try

sapply(strsplit(x, "\\s+"), length)
## [1] 6 2 1 1
like image 38
CHP Avatar answered Nov 10 '22 22:11

CHP