2
$\begingroup$

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!!

$\endgroup$
1
  • $\begingroup$ The question headline is a little misleading, since this is not what the accepted answer is doing. $\endgroup$ Jun 12, 2019 at 19:23

2 Answers 2

1
$\begingroup$
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..

$\endgroup$
0
$\begingroup$

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
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.