Mutate in R conditional

Viewed 433

I have a dataframe df with columns payment_type and payment_amount.

I want to do a conditional mutate such that if payment_type is "tpt" or "trt", it should make the payment_amount 5 times.

df$payment_amount<-df%>%select(payment_amount)%>%filter(payment_type=='tpt' | payment_type=='trt')%>%mutate(payment_amount=payment_amount*100)

But this isn't working. TIA

2 Answers

Try

df %>%
  mutate(pament_amount = case_when(
    payment_type == "tpt" | payment_type == "trt" ~ 5 * payment_amount,
    TRUE ~ payment_amount
  ))

Approach based on question

df$payment_amount[(df$payment_type=='tpt' | df$payment_type == "trt")]<- df %>%
  filter(payment_type=='tpt' | payment_type=='trt')%>%
  select(payment_amount)%>%
  mutate(payment_amount=payment_amount*100) %>% pull

Here is an alternative to Park's answer with %in%.

df %>%
  mutate(pament_amount = case_when(
    payment_type %in% c("tpt" "trt") ~ 5 * payment_amount,
    TRUE ~ payment_amount
  ))
Related