luciano
luciano

Reputation: 13792

Replacing more than one elements with replace function

In mtcars$am I want to replace instances of 0 with zero and instances of 1 with one. This is what I tried:

library(dplyr)

mtcars %>%
dplyr::select(am) %>%
mutate(am.character = replace(am, am %in% c(0, 1), c("zero", "one"))) %>%
as.data.frame

   am am.character
1   1         zero
2   1          one
3   1         zero
4   0          one
5   0         zero
6   0          one
7   0         zero
8   0          one
9   0         zero
10  0          one
11  0         zero
12  0          one
13  0         zero
14  0          one
15  0         zero
16  0          one
17  0         zero
18  1          one
19  1         zero
20  1          one
21  0         zero
22  0          one
23  0         zero
24  0          one
25  0         zero
26  1          one
27  1         zero
28  1          one
29  1         zero
30  1          one
31  1         zero
32  1          one

But all this has done is created a vector of c(zero, one) that is repeated 16 times. How can I replace instances of 0 with zero and instances of 1 with one?

Upvotes: 1

Views: 433

Answers (1)

akrun
akrun

Reputation: 886948

You can try by numeric indexing.

 mtcars %>% 
    select(am) %>% 
    mutate(am1= c('zero', 'one')[am+1L])

Or using replace, but this is not useful when there are multiple elements to replace. Best would be to use factor and specify the levels/labels.

 mtcars %>%
      select(am) %>%
      mutate(am1= replace(replace(am, !am, 'zero'), am==1, 'one') )

Or instead of double replace, create a column of zero and replace the zero' byone` based on values of "am"

 mtcars %>%
     select(am) %>% 
     mutate(am1= 'zero', am1=replace(am1, am!=0, 'one'))

Other option where you can change multiple elements with corresponding replacement element is mgsub from qdap

 library(qdap)
  mtcars %>%
        select(am) %>%
        mutate(am1= mgsub(0:1, c('zero', 'one'), am))

Update

If you need to use replace to change the values in one variable based on the other,

mtcars %>% 
       select(am,gear) %>%
       mutate(am= replace(am, gear %in% 4:5, 1000))

Upvotes: 3

Related Questions