FMM
FMM

Reputation: 2005

Apply formula if meet criteria in R

I have the following data set:

df1 <- list(
  x = seq(0,100, length.out = 1500),
  y = seq(0,500, length.out = 1500),
  z = rep(letters[1], length.out = 1500)
) 

df2 <- list(
  x = seq(0,100, length.out = 1480),
  y = seq(400,800, length.out = 1480),
  z = rep(letters[2], length.out = 1480)
)

df3 <- dplyr::bind_rows(df1,df2)

I need to apply a function in df3, let's say, I need to divide the column y by 200 if it meets the criterion of z == 'b'.

Any idea how I can achieve this?

Upvotes: 0

Views: 77

Answers (1)

Emi
Emi

Reputation: 3574

You can also try case_when which is extendible to more than two cases.

library(dplyr)
df3 <- df3 %>% 
     mutate(y = case_when(z=="b" ~ y / 200,
                          TRUE ~ y))

Upvotes: 1

Related Questions