jeudi 13 mai 2021

How to fill mean for NAs in column by groups in r?

Greetings of the day

I have a dataset with several NAs I want to take mean for each column and fill Nas by specific groups my dataset looks as below

PID Category    column1 column2 column3
123    1             54    2.4  24.5
324    1             52    NA   NA
356    1             NA    NA   NA
378    2             56    3.2  NA
395    2             NA    3.5  NA
362    2             NA    8.9  NA
789    3             65   12.6  23.8
759    3             66    NA   26.8
762    3             67    NA   27.2
741    3             69   8.5   23.3

I need desired output

PID Category    column1 column2 column3
123    1             54   2.4   24.5
324    1             52   6.5   25.1
356    1             61.3 6.5   25.1
378    2             56   3.2   25.1
395    2             61.3 3.5   25.1
362    2             61.3 8.9   25.1
789    3             65  12.6   23.8
759    3             66   6.5   26.8
762    3             67   6.5   27.2
741    3             69   8.5   23.3

Thanks

Aucun commentaire:

Enregistrer un commentaire