Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace one element in vector with multiple elements

Tags:

replace

r

gsub

I have a vector where I want to replace one element with multiple element, I am able to replace with one but not multuiple, 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"

However

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
like image 490
user1165199 Avatar asked Feb 13 '18 13:02

user1165199


People also ask

How do you replace an element in a vector?

To replace an element in Java Vector, set() method of java. util. Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.

How do I replace a specific value in a vector in R?

Replace the Elements of a Vector in R Programming – replace() Function. replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.

How do you replace a specific value in a vector C++?

The best option to conditionally replace values in a vector in C++ is using the std::replace_if function. It assigns a new value to all the elements in the specified range for which the provided predicate holds true .

Is there a Replace function in R?

The replace() function in R syntax is very simple and easy to implement. It includes the vector, index vector, and the replacement values as well as shown below.


1 Answers

Here's how I would tackle it:

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're making use of the fact that list-structures are more flexible than atomic vectors. We can replace a length-1 list-element with a length>1 element and then unlist the result to go back to an atomic vector.

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

like image 99
talat Avatar answered Sep 28 '22 04:09

talat