WillyWonka
WillyWonka

Reputation: 107

Replacing an element in a character string by the previous value

I have a character string looking like this:

string <- c("1","2","3","","5","6","")

I would like to replace the gaps by the previous value, obtaining a string similar to this:

string <- c("1","2","3","3","5","6","6")

I have adjusted this solution (Replace NA with previous and next rows mean in R) and I do get the correct result:

string <- as.data.frame(string)
ind <- which(string == "")
string$string[ind] <- sapply(ind, function(i) with(string, string[i-1]))

This way is however quite cumbersome and there must be an easier way that does not require me to transform the string to a data frame first. Thanks for your help!

Upvotes: 1

Views: 198

Answers (1)

akrun
akrun

Reputation: 887028

We can use na.locf from zoo after changing the blank ("") to NA so that the NA values get replaced by the non-NA adjacent previous values

library(zoo)
na.locf(replace(string, string =="", NA))
#[1] "1" "2" "3" "3" "5" "6" "6"

If there is only atmost one blank between the elements, then create an index as in the OP's post and then do the replacement by the element corresponding to the index subtracted 1

i1 <- which(string == "")
string[i1] <- string[i1-1]

Upvotes: 4

Related Questions