strsplit - R Split string and keep substrings righthand of match? -


how stringsplit() in r? stop splitting when no first names seperated dashes remain. keep right hand side substring given in results.

a <- c("tim/tom meyer xy900 123kncjd", "sepp/max/peter moser vk123 456xyz")  # result:  c("tim meyer xy900 123kncjd", "tom meyer xy900 123kncjd", "sepp moser vk123 456xyz", "max moser vk123 456xyz", "peter moser vk123 456xyz") 

here 1 possibility using few of different base string functions.

## lengths of output each first name len <- lengths(gregexpr("/", sub(" .*", "", a), fixed = true)) + 1l ## extract first names  ## using fact end @ first space character fn <- scan(text = a, sep = "/", = "", comment.char = " ") ## paste them paste0(fn, rep(regmatches(a, regexpr(" .*", a)), len)) # [1] "tim meyer xy900 123kncjd" "tom meyer xy900 123kncjd" # [3] "sepp moser vk123 456xyz"  "max moser vk123 456xyz"   # [5] "peter moser vk123 456xyz" 

addition: here second possibility, using little less code. might little faster too.

s <- strsplit(a, "\\/|( .*)") paste0(unlist(s), rep(regmatches(a, regexpr(" .*", a)), lengths(s))) # [1] "tim meyer xy900 123kncjd" "tom meyer xy900 123kncjd" # [3] "sepp moser vk123 456xyz"  "max moser vk123 456xyz"   # [5] "peter moser vk123 456xyz" 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -