I have a string in R as
x <- "The length of the word is going to be of nice use to me"
I want the first 10 words of the above specified string.
Also for example I have a CSV file where the format looks like this :-
Keyword,City(Column Header)
The length of the string should not be more than 10,New York
The Keyword should be of specific length,Los Angeles
This is an experimental basis program string,Seattle
Please help me with getting only the first ten words,Boston
I want to get only the first 10 words from the column 'Keyword' for each row and write it onto a CSV file. Please help me in this regards.
Regular expression (regex) answer using \w
(word character) and its negation \W
:
gsub("^((\\w+\\W+){9}\\w+).*$","\\1",x)
^
Beginning of the token (zero-width)((\\w+\\W+){9}\\w+)
Ten words separated by not-words.
(\\w+\\W+){9}
A word followed by not-a-word, 9 times
\\w+
One or more word characters (i.e. a word)\\W+
One or more non-word characters (i.e. a space){9}
Nine repetitions\\w+
The tenth word.*
Anything else, including other following words$
End of the token (zero-width)\\1
when this token found, replace it with the first captured group (the 10 words)How about using the word
function from Hadley Wickham's stringr
package?
word(string = x, start = 1, end = 10, sep = fixed(" "))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With