Home > Mobile >  How to mutate a column with if/then in R Data.frame
How to mutate a column with if/then in R Data.frame

Time:12-14

Lets suppose if the data is

data <- head(iris)

How can i create a new column whose values will be derived from data$Sepal.Length in a way that if data$Sepal.Length is equal to or greater than 5, value will be 5 and if its less or equal to 3, value will be 3, else values should remain same... I have tried

data %>% mutate(Sepal.Length = case_when(Sepal.Length <=3 ~ '3',Sepal.Length>=5 ~ '5'))

But it is giving NA to remaining values..

CodePudding user response:

You can do this using a basic case_when statement:

data %>% 
  mutate(Sepal.Length = case_when(
    Sepal.Length <= 3 ~ 3,
    Sepal.Length >= 5 ~ 5,
    TRUE ~ Sepal.Length))

#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1            5         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5            5         3.6          1.4         0.2  setosa
# 6            5         3.9          1.7         0.4  setosa```
  • Related