Dan Lewer - 3 months ago 11

R Question

I've been looking for a function that replaces specific values of a vector. For example, you have a character vector including the values

`A`

`B`

`C`

`D`

`NA`

`A`

`E`

`NA`

`F`

I've tried to write a function and came up with the below. It seems to work OK, but has problems, including that it turns factors into characters.

`recode <- function(x, old, new) {`

u <- rep(NA, length(x))

for (i in 1:length(old)) {

if(is.na(old[i])) {

u[is.na(x)] <- new[i]

} else {

u[x == old[i]] <- new[i]

}

}

return(ifelse(x %in% old, u, x))

}

For example:

`a <- sample(c("A", "B", "C", "D", NA), 20, replace = T)`

recode(a, old = c("A", NA), new = c("E", "F"))

Perhaps there is already a function that does this and I just haven't found it! Or does anyone know a sensible way to do this?

Answer

I suggest you use `dplyr::recode`

in the newer version of `dplyr`

.

```
library(dplyr)
a <- sample(c("A", "B", "C", "D", NA), 20, replace = T)
recode(a, A = "E", .missing = "F")
```

Note that there is also `dplyr::recode_factor`

, which has a couple of factor-specific features (maintains order).