Replace one element in a vector with several elements

I have a vector where I want to replace one element with several elements, I can replace it with one, but not multi-level, can anyone help?

For example, I have

data <- c('a', 'x', 'd') > data [1] "a" "x" "d" 

I want to replace "x" with "b", "c" to get

 [1] "a" "b" "c" "d" 

but

 gsub('x', c('b', 'c'), data) 

gives me

 [1] "a" "b" "d" Warning message: In gsub("x", c("b", "c"), data) : argument 'replacement' has length > 1 and only the first element will be used 
+7
replace r gsub
source share
4 answers

Here's how I would handle this:

 data <- c('a', 'x', 'd') lst <- as.list(data) unlist(lapply(lst, function(x) if(x == "x") c("b", "c") else x)) # [1] "a" "b" "c" "d" 

We use the fact that list structures are more flexible than atomic vectors. We can replace the length-1 list item with length> 1, and then list the result to return to the atomic vector.

Since you want to replace the exact matches with "x", I prefer not to use sub / gsub in this case.

+3
source share

You can try this, although I believe the accepted answer is great:

 unlist(strsplit(gsub("x", "bc", data), split = " ")) 

Logic : replacing “x” with “bc” with a space, and then doing strsplit, after separating it, we can convert it back to vector using unlist.

+2
source share

This is a bit complicated because in your replacement you also want to develop your vector. However, I believe that this should work:

 replacement <- c("b","c") new_data <- rep(data, times = ifelse(data=="x", length(replacement), 1)) new_data[new_data=="x"] <- replacement new_data #[1] "a" "b" "c" "d" 

This will also work if there are multiple "x" in your vector:

 data <- c("a","x","d","x") 
+1
source share

Another approach:

 data <- c('a', 'x', 'd') pattern <- "x" replacement <- c("b", "c") sub_one_for_many <- function(pattern, replacement, x) { removal_index <- which(x == pattern) if (removal_index > 1) { result <- c(x[1:(removal_index-1)], replacement, x[(removal_index+1):length(x)]) } else if (removal_index == 1) { result <- c(replacement, x[2:length(x)]) } return(result) } answer <- sub_one_for_many(pattern, replacement, data) 

Output:

 > answer [1] "a" "b" "c" "d" 
0
source share

All Articles