Replace given value in vector

r replace multiple values in vector
r replace values in vector condition
replace values in r
r replace values in column
r replace values in dataframe column
replace value in vector c++
replace row values in r
dplyr replace multiple values

I'm looking for a function which will replace all occurrences of one value with another value. For example I'd like to replace all zeros with ones. I don't want to have to store the result in a variable, but want to be able to use the vector anonymously as part of a larger expression.

I know how to write a suitable function myself:

> vrepl <- function(haystack, needle, replacement) {
+   haystack[haystack == needle] <- replacement
+   return(haystack)
+ }
> 
> vrepl(c(3, 2, 1, 0, 4, 0), 0, 1)
[1] 3 2 1 1 4 1

But I'm wondering whether there is some standard function to do this job, preferrably from the base package, as an alternative from some other commonly used package. I believe that using such a standard will likely make my code more readable, and I won't have to redefine that function wherever I need it.

Perhaps replace is what you are looking for:

> x = c(3, 2, 1, 0, 4, 0)
> replace(x, x==0, 1)
[1] 3 2 1 1 4 1

Or, if you don't have x (any specific reason why not?):

replace(c(3, 2, 1, 0, 4, 0), c(3, 2, 1, 0, 4, 0)==0, 1)

Many people are familiar with gsub, so you can also try either of the following:

as.numeric(gsub(0, 1, x))
as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0)))
Update

After reading the comments, perhaps with is an option:

with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))

Replace given value in vector, Perhaps replace is what you are looking for: > x = c(3, 2, 1, 0, 4, 0) > replace(x, x​==0, 1) [1] 3 2 1 1 4 1. Or, if you don't have x (any specific  Parameters first, last Forward iterators to the initial and final positions in a sequence of elements that support being compared and assigned a value of type T.The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.

Another simpler option is to do:

 > x = c(1, 1, 2, 4, 5, 2, 1, 3, 2)
 > x[x==1] <- 0
 > x
 [1] 0 0 2 4 5 2 0 3 2

7.3 Changing values of a vector, replace replaces the values in x with indices given in list by those given in values . If necessary, the values in values are recycled. Usage. replace(x, list, values)  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Replacing elements in vector using erase and insert

To replace more than one number:

vec <- 1:10
replace(vec, vec== c(2,6), c(0,9)) #2 and 6 will be replaced by 0 and 9.

Edit:

for a continous series, you can do this vec <- c(1:10); replace(vec, vec %in% c(2,6), c(0,9)) but for vec <- c(1:10,2,2,2); replace(vec, vec %in% c(2,6), 0) we can replace multiple values with one value.

How to Change Values in a Vector in R, Now that you know how to index a vector, you can easily change specific values in a vector using the assignment ( <- ) operation. To do this, just assign a vector  Replace Values in a Vector. replace replaces the values in x with indices given in list by those given in values.If necessary, the values in values are recycled.

Why the fuss?

replace(haystack, haystack %in% needles, replacements)

Demo:

haystack <- c("q", "w", "e", "r", "t", "y")
needles <- c("q", "w")
replacements <- c("a", "z")

replace(haystack, haystack %in% needles, replacements)
#> [1] "a" "z" "e" "r" "t" "y"

replace function, The assignment to a specific index is actually a function as well. It's different, however, from the brackets function because you also give the replacement values  std::replace_if only supports replacing elements with the constant value specified as last argument. However, if you feel that it makes any sense for you, you can write your own replace_if function based on the reference implementation and make it accept some kind of generator as a last parameter.

A simple way to do this is using ifelse, which is vectorized. If the condition is satisfied, we use a replacement value, otherwise we use the original value.

v <- c(3, 2, 1, 0, 4, 0)
ifelse(v == 0, 1, v)

We can avoid a named variable by using a pipe.

c(3, 2, 1, 0, 4, 0) %>% ifelse(. == 0, 1, .)

A common task is to do multiple replacements. Instead of nested ifelse statements, we can use case_when from dplyr:

case_when(v == 0 ~ 1,
          v == 1 ~ 2,
          TRUE ~ v)

Old answer:

For factor or character vectors, we can use revalue from plyr:

> revalue(c("a", "b", "c"), c("b" = "B"))
[1] "a" "B" "c"

This has the advantage of only specifying the input vector once, so we can use a pipe like

x %>% revalue(c("b" = "B"))

std::replace and std::replace_if in C++, Replace Values in a Vector. replace replaces the values in x with indices given in list by those given in values . If necessary, the values in values are recycled. Consider the following vector: A=[6 8 12 -9 0 5 4 -3 7 -1] Write a program using a for loop to produce a new vector, B which is related to A in the following way: All values of A which are not less than 1 should be replaced with the natural logarithm of that number, all numbers that are less than 1 should be replaced with the original number

std::replace - replace, Queries for elements having values within the range A to B in the given index range If elements that needs to be replace is found then element 30 30 20 10 10 20 Output : 10 99 30 30 99 10 10 99 // Replaced value 20 in vector to 99. CPP program to find and replace the value Function used to replace the values​. void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value) first, last : Forward iterators to the initial and final positions in a sequence of elelments. old_value : Value to be replaced. new_value : Replacement value. Return Value : This function do not return any value.

Replace Values in Vector on Specific Place in R, By continuing, you give permission to deploy cookies, as detailed in our privacy policy. ok template <class ForwardIterator, class T> void replace (​ForwardIterator first, for (std::vector< int >::iterator it=myvector.begin(); it!=​myvector.end(); ++it) std::cout replace_copy: Copy range replacing value (​function template ). replace: Replace Values in a Vector Description Usage Arguments Value Note References Description. replace replaces the values in x with indices given in list by those given in values. If necessary, the values in values are recycled. Usage

Replace certain elements of vector with the values from another , You have a data frame with 4 columns, each columns has 25 rows. You want to replace every 5th element with an outlying value (the mean of the column). Changing values in a vector in R is actually pretty simple. To illustrate, let’s assume that you created two vectors containing the number of baskets that Granny and Geraldine made in six basketball games, as follows: > baskets.of.Granny <- c(12,4,4,6,9,3) > baskets.of.Geraldine <- c(5,3,2,2,12,9) But suppose that Granny tells you that you made a mistake: …

Comments
  • Is something like as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0))) useful?
  • vec[vec==vec]<-replacement
  • Remember that this doesn't change x unless reassigned.
  • The specific reason why not to name x is that the expression computing x might itself be rather long. And I want to avoid clobbering my namespace with too many variables. So I had hoped for a way to avoid having to name the vector, or having to duplicate its expression. gsub and its character intermediate doesn't feel right either, in terms of performance as well as precision, particularly when dealing with floating point numbers.
  • I definitely could and should use replace in my own vrepl implementation, unless someone will come up with an answer which obsoletes my own function altogether. So thanks for pointing that out!
  • @MvG, what about: with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))?
  • This requires saving the intermediate result to a named variable, which I want to avoid, as I stated in my question.
  • @MvG: sorry, missed that part. Anyway it is much more maintainable to save it in a variable
  • >Warning message: In replace(vec, vec == c(2, 6), c(0, 9)) : number of items to replace is not a multiple of replacement length
  • Note this answer assumes needles and replacements are 1-to-1 (recycling vectors if necessary).
  • I'll vote you up for using plyr in 2018 - must be hard living under a stone :p
  • @MSBerends since dplyr works (mainly) with dataframes I'm not aware of a dplyr solution
  • I would have to give the same vector twice, once for the test argument, and once as one of the result arguments, right? Doesn't seem any easier than the replace call mrdwab suggested.
  • Correct, but you could save it in a temporary variable and just reference that twice. ifelse and replace will both do the job.