lundi 20 août 2018

Applying mutate_at conditionally to specific rows in a dataframe in R

I have a dataframe in R that looks like the following:

a  b  c  condition
1  4  2  acap
2  3  1  acap
2  4  3  acap
5  6  8  ncap
5  7  6  ncap
8  7  6  ncap

I am trying to recode the values in columns a, b, and c for condition ncap (and also 2 other conditions not pictured here) while leaving the values for acap alone.

The following code works when applied to the first 3 columns. I am trying to figure out how I can apply this only to rows that I specify by condition while keeping everything in the same dataframe.

df = df %>%
     mutate_at(vars(a:c), function(x) 
     case_when x == 5 ~ 1, x == 6 ~ 2, x == 7 ~ 3, x == 8 ~ 4)

I've looked around for an answer to this question and am unable to find it. If someone knows of an answer that already exists, I would appreciate being directed to it.

Aucun commentaire:

Enregistrer un commentaire