简体   繁体   中英

Using replace in R multiple times in function

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM