Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace values in a vector based on another vector

Tags:

replace

r

I would like to replace values in a vector (x) with values from another vector (y). Catch 22: The methods needs to be dynamic to accommodate different number of "levels" in vector x. For instance, consider vector x

x <- sample(c(1, 2, 3, 4, 5), 100, replace = TRUE)
> x
  [1] 2 4 1 1 3 1 1 1 1 1 2 2 5 5 4 5 5 3 4 1 2 2 3 3 3 5 1 3 4 5 5 3 2 4 3 1 3
 [38] 1 4 5 4 1 4 5 4 5 2 4 2 5 3 4 3 1 2 1 1 5 1 4 2 2 5 2 2 4 5 2 4 5 2 5 4 1
 [75] 3 3 4 4 1 1 4 4 2 4 5 4 5 5 4 2 5 2 4 5 3 2 1 1 2 2

where I would like to replace 1s with 100, 2s with 200 and so on.

This can be done easily with a for loop but for large vectors, several 100 thousand values, this is highly inefficient. Any tips how to optimize the code?

x <- sample(c(1, 2, 3, 4, 5), 100, replace = TRUE)
y <- c(100, 200, 300, 400, 500)
x.lvl <- c(1, 2, 3, 4, 5)
x.temp <- x

for (i in 1:length(y)) {
    x.temp[which(x == x.lvl[i])] <- y[i]
}
like image 286
Roman Luštrik Avatar asked Oct 11 '10 09:10

Roman Luštrik


People also ask

How do you overwrite a vector value?

To replace a value in an R vector, we can use replace function. It is better to save the replacement with a new object, even if you name that new object same as the original, otherwise the replacements will not work with further analysis.

How do I replace data 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 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 . For example, the following code replaces all values greater than 5 with 10.

How do you set a value in a vector in R?

There are different ways of assigning vectors. In R, this task can be performed using c() or using “:” or using seq() function. Generally, vectors in R are assigned using c() function. In R, to create a vector of consecutive values “:” operator is used.


1 Answers

Try with match

y[match(x, x.lvl)]
like image 169
Marek Avatar answered Sep 19 '22 17:09

Marek