9

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?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user3664020
  • 2,980
  • 6
  • 24
  • 45
  • 4
    `sapply(strsplit(str, " "), length)` works for me. – Roman Luštrik May 22 '14 at 08:43
  • @RomanLuštrik what if string has multiple spaces in between few words? for example. str <- c("this is a string current trey", "feather rtttt", "tusla", "laq") Then it does not work. It counts those extra spaces too. I hope you get it what i am trying to say. – user3664020 May 22 '14 at 08:50
  • @user3664020, the answer is in the question you have linked. `str1 <- gsub(' {2,}',' ',str); sapply(strsplit(str1, " "), length)`. Also, `str` is a stored function in R, please try to refrain from storing your strings in there – David Arenburg May 22 '14 at 08:59
  • Using `"\\s+"` instead of `" "` in `strsplit` will allow you to consider and ignore multiple spaces between words. – BenBarnes May 22 '14 at 09:07

3 Answers3

13

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
CHP
  • 16,981
  • 4
  • 38
  • 57
11

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
Spacedman
  • 92,590
  • 12
  • 140
  • 224
1

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
David Buck
  • 3,752
  • 35
  • 31
  • 35
Sdae
  • 21
  • 3