hereforadoubt
hereforadoubt

Reputation: 123

Mutate in R conditional

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

Upvotes: 7

Views: 1562

Answers (2)

Kra.P
Kra.P

Reputation: 15123

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

Upvotes: 4

Rui Barradas
Rui Barradas

Reputation: 76402

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

Upvotes: 4

Related Questions