Replacing multiple items with a 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 been done, the vector c (zero, one) is created, which is repeated 16 times. How to replace instances 0 with zero and instances 1 with one?

0
source share
1 answer

You can try indexing numeric .

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

Or using replace , but this is not useful when replacing multiple elements. It would be best to use factor and specify 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 zero' by one` based on the values ​​of "am"

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

Another option where you can change multiple elements with the 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 values ​​in one variable based on another,

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

Source: https://habr.com/ru/post/1258463/


All Articles