Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
850 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...