Search code examples
rreplaceconditional-statementsmagrittr

Conditionally replace values using magrittr


Suppose I have a dataframe I would like to perform transformations on. Normally it would look like:

a <- data.frame(c(NA, 0,1), c(34,NA,0), c(3,9,NA) )
b <- c('key1', 'key2', 'key3')
####replace NA values with 0
a[is.na(a)] <- 0
####replace 1 with 2
a[a==1] <- 2
####sum rows
a <- rowSums(a)
####bind b as key column for joining datasets in a later stage
c <- cbind(b, a)

Now my question is: how do I translate this to magrittr?

library(magrittr)
c %>% 
.[is.na] %>% 0 %>% .[.==1] %>% 2 %>%
rowSums %>% cbind(b, .)

gives me:

Error in .[is.na(.)] : object of type 'builtin' is not subsettable
In addition: Warning message:
In is.na(.) : is.na() applied to non-(list or vector) of type 'builtin'


Solution

  • We can use dplyr

    library(dplyr)
    a %>%
        mutate_each(funs(replace(., is.na(.), 0))) %>% 
        mutate_each(funs(replace(., .==1, 2))) %>%
        rowSums(.) %>%
        data_frame(key = b, val = .)
    #    key   val
    #   <chr> <dbl>
    #1  key1    37
    #2  key2     9
    #3  key3     2
    

    Or without using the dplyr functions

     a %>% 
        is.na(.) %>%
        replace(a, ., 0) %>%
        replace(., .==1, 2) %>%
        rowSums() %>% 
        cbind(b, .)