if statement - Mutate multiple columns with a certain condition in R -


i have data

m1  m2  m3 ucl 1   2   3   1.5 

i make new columns condition:

if m1 more ucl, mm1 "up" , otherwise "null"

if m2 more ucl, mm2 "up" , otherwise "null"

if m3 more ucl, mm3 "up" , otherwise "null"

m1  m2  m3 ucl   | mm1  mm2 mm3 1   2   3   1.5  | null  

but have several m column (like m1~m1005) make code such mutate_each , mutate_at. how use function using mutate , ifelse in order make new columns under particular condition?

here simple dplyr solution. note easier add suffix new variables e.g. m1_m rather mm1. however, can set colnames afterwards if keen rename them (see e.g. here on how that).

i show result tibble can see column types. note once new column has both up , na in it, change logical type character type.

library(dplyr)  textdata <- "m1  m2  m3 ucl 1   2   3   1.5"  mydf <- read.table(text = textdata, header = t)  mydf %>%      mutate_if(is.integer, as.numeric) %>%      mutate_at(vars(starts_with("m")), funs(m = ifelse(. > ucl, "up", na))) %>%      tibble::as.tibble()  # tibble: 1 x 7      m1    m2    m3   ucl  m1_m  m2_m  m3_m   <dbl> <dbl> <dbl> <dbl> <lgl> <chr> <chr> 1     1     2     3   1.5    na       

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -