下面是一個使用幾個不同的基本字符串函數的一種可能性。
## get the lengths of the output for each first name
len <- lengths(gregexpr("/", sub(" .*", "", a), fixed = TRUE)) + 1L
## extract all the first names
## using the fact that they all end at the first space character
fn <- scan(text = a, sep = "/", what = "", comment.char = " ")
## paste them together
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"
增加:這是第二個可能性,使用少的代碼。可能會更快一點。
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"
完美! ..no循環和基函數正是我以後;) – Kay
好的解決方案理查德 –
第二個解決方案是金錢1加 –