I have a character vector listed below.
vec <- c(
'red yellow orange', 'green white', 'blue', 'orange purple', 'green brown', 'red'
)
I would like to paste blue
and red
in front of the string that precedes them. Here is my expected output.
[1] "red yellow orange" "blue green white" "blue" "orange purple" "red green brown" "red"
CodePudding user response:
with ifelse and head_tail
c(ifelse(
grepl("^red|blue$", tail(vec,-1)),
paste(tail(vec,-1), head(vec,-1)),
head(vec, -1)), tail(vec,1))