0

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'

989
  • 12,579
  • 5
  • 31
  • 53
DaReal
  • 597
  • 3
  • 10
  • 24

2 Answers2

4

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, .)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thank you, I do prefer a way without using another package. The replace function is what I was looking for. – DaReal Jul 14 '16 at 12:18
2

A slightly quicker (in terms of typing, not sure if it's also faster in terms of computation) way than suggested by @akrun is using the rec function from the sjmisc-package:

library(sjmisc)
library(dplyr)

a <- data.frame(c(NA, 0,1), c(34,NA,0), c(3,9,NA) )
b <- c('key1', 'key2', 'key3')

a %>% 
  rec("NA=0;1=2;else=copy") %>% 
  rowSums(.) %>% 
  data_frame(key = b, val = .)

# A tibble: 3 x 2
#     key   val
#   <chr> <dbl>
# 1  key1    37
# 2  key2     9
# 3  key3     2
Daniel
  • 7,252
  • 6
  • 26
  • 38
  • Thank you, I will keep this one in mind for when I have a larger list of replacements to make. – DaReal Jul 14 '16 at 12:30