lundi 22 juin 2020

Mutate_at and ifelse problem with vectorization

I thinks that is easier if i show, what is the problem, So I have this numeric data

  MoSold YrSold SalePrice OverallQual OverallCond
1      2      3    208500           7           5
2      5      2    181500           6           8
3      9      3    223500           7           5
4      2      1    140000           7           5
5     12      3    250000           8           5
6     10      4    143000           5           5

thanks to mutate_at and a nested ifelse i would like to change each row if condition is true (the column mean is higher than 0.8) however when i try to do it whith this code

data %>% 
  mutate_at(vars(MoSold, YrSold, SalePrice, OverallQual, OverallCond), 
            ~(ifelse((mean(., na.rm = T)) > 4, log(.), .))) %>% head()

I get the following data, all the columns have the same value

     MoSold YrSold SalePrice OverallQual OverallCond
1 0.6931472      3  12.24769     1.94591    1.609438
2 0.6931472      3  12.24769     1.94591    1.609438
3 0.6931472      3  12.24769     1.94591    1.609438
4 0.6931472      3  12.24769     1.94591    1.609438
5 0.6931472      3  12.24769     1.94591    1.609438
6 0.6931472      3  12.24769     1.94591    1.609438

and i would like to have the log of the corresponing value for each row if the condition is true and the raw value if condition is false

I know that one solution is to use a for loop but a would really like a solution with dplyr/tidyverse

Thanks in advance

I.

Aucun commentaire:

Enregistrer un commentaire