anupam
anupam

Reputation: 135

condititonal concatenation of vector depending upon NA position in other vector

i have a two vectors , i desire a third vector that is conditional upon NA position of first vector

a= c(1,2,NA,NA,3,NA,NA,5)
b= c("a","b","c","d","e","f","g","h")


desired output= c("a","b c d",NA,NA,"e f g",NA,NA,"h")

Upvotes: 1

Views: 46

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

We can use grouping via zoo::na.locf() to paste the values together through tapply(). Then we replace them in the original vector.

replace(a, !is.na(a), tapply(b, zoo::na.locf(a), paste, collapse = " "))
# [1] "a"     "b c d" NA      NA      "e f g" NA      NA      "h"    

Upvotes: 2

Andrew Gustar
Andrew Gustar

Reputation: 18425

In base R you could do this...

x <- a
x[!is.na(a)] <- tapply(b, cumsum(!is.na(a)), paste, collapse=" ")

x
[1] "a"     "b c d" NA      NA      "e f g" NA      NA      "h"  

Upvotes: 0

Related Questions