Divide a column by itself with mutate_at dplyr

Hi I'd like to turn each non zero value of my selected columns to a 1 using mutate_at()

 BRAND  MEDIA_TYPE    INV1       INV2
   chr  chr      dbl     dbl
  b1     newspapers    2         27
  b1     magazines     3         0
  b2     newspapers    0         0
  b3     tv            1        145
  b4     newspapers    4         40
  b5     newspapers    5         0
  b1     newspapers    1         0
  b2     newspapers    0         28

The final result should be like follow:

 BRAND  MEDIA_TYPE    INV1      INV2
   chr  chr      dbl     dbl
  b1     newspapers    1         1
  b1     magazines     1         0
  b2     newspapers    0         0
  b3     tv            1         1
  b4     newspapers    1         1
  b5     newspapers    1         0
  b1     newspapers    1         0
  b2     newspapers    0         1

Do you have any suggestion on how to solve it? Thank you!!

Topic dplyr dataframe programming r

Category Data Science


An alternative approach in case you not have column that starts_with some name a practical approach is doing this:

df %>% mutate(INV1 = INV1/INV1, INV2 = INV2/INV2) %>% 
 replace(is.na(.), 0) 
 
df = tibble(
            `BRAND` = c('b1','b1','b2','b3','b4','b5','b1','b2'),
            `MEDIA_TYPE` = c('newspapers','magazines','newspapers',
            'tv','newspapers','newspapers','newspapers','newspapers'),
            `INV1` = c(2,3,0,1,4,5,1,0),
            `INV2` = c(27,0,0,145,40,0,0,28)
            ) 
#The replace(is.na(.), 0) 
#is for replace NaN resulting of division by 0

Output: 

# A tibble: 8 x 4
  BRAND MEDIA_TYPE  INV1  INV2
  <chr> <chr>      <dbl> <dbl>
1 b1    newspapers     1     1
2 b1    magazines      1     0
3 b2    newspapers     0     0
4 b3    tv             1     1
5 b4    newspapers     1     1
6 b5    newspapers     1     0
7 b1    newspapers     1     0
8 b2    newspapers     0     1

mutate_at(my_data, vars(starts_with("INV")), sign)

Although I see your INV1 column is a date? I'm not sure how much that'll affect things..

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.