Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract first 2 words from a string in R?

Tags:

string

r

I need to extract first 2 words from a string. If the string contains more than 2 words, it should return the first 2 words else if the string contains less than 2 words it should return the string as it is.

I've tried using 'word' function from stringr package but it's not giving the desired output for cases where len(string) < 2.

word(dt$var_containing_strings, 1,2, sep=" ")

Example: Input String: Auto Loan (Personal)
Output: Auto Loan

Input String: Others Output: Others

like image 358
awadhesh204 Avatar asked Dec 10 '22 02:12

awadhesh204


1 Answers

If you want to use stringr::word(), you can do:

ifelse(is.na(word(x, 1, 2)), x, word(x, 1, 2))

[1] "Auto Loan" "Others" 

Sample data:

x <- c("Auto Loan (Personal)", "Others")
like image 50
tmfmnk Avatar answered Dec 12 '22 14:12

tmfmnk