0

I take the iris dataframe and apply a transformation to the Sepal.Length column as below to create a new column called Sepal.Length2. If I want to do the same transformation to the Sepal.Width, Petal.Length and Petal.Width columns, how do I go about this without copying the case_when statement out another 3 times?

library(tidyverse)
iris<-iris%>%
  mutate(Sepal.Length2=case_when(Sepal.Length<=5~"Less than 5",TRUE~"More than 5"))

Adding the solution here to help others:

iris<-iris%>%
  mutate(across(c(Sepal.Length, Sepal.Width, Petal.Length,Petal.Width), 
               ~ case_when(. <=5~"Less than 5", 
               TRUE~"More than 5"),
               .names="{.col}_1"))
Basil
  • 590
  • 2
  • 15

0 Answers0