Reputation: 403
I'm trying to use R's replace multiple times in a function, but only the last use seems to work. For instance, using x where
x <- c(1:3)
if I wanted to add one to each odd value, I tried
test <- function(x) {
replace(x,x==1,2)
replace(x,x==3,4)
}
but test(x) results in (1,2,4) where I wanted it to be (2,2,4)--in other words, only the last "replace" seems to be working. I know I could refer to the values by location within the vector, but anyone know how to fix this if I want to refer to the values themselves?
Thanks so much!
Upvotes: 0
Views: 250
Reputation: 2056
you need to assign the output of the replace function to a variable
x <- c(1:3)
test <- function(x) {
x <- replace(x,x==1,2)
replace(x,x==3,4)
}
test(x)
[1] 2 2 4
Or using the case_when
function from dplyr
library(dplyr)
case_when(x == 1 ~ 2,
x == 3 ~ 4,
TRUE ~ as.double(x))
[1] 2 2 4
Upvotes: 1