Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How create a IF and then function in R

I would like to create a function for generating new columns based on values from existing column.

Following example below:

day1  weight1
20       .
25      190
26      167
27      189
28      200
60      300
120     127 

conditions -> IF day1 > 20 AND day1 < 200 then weightAdj = weight1; (code extracted from SAS)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output:

day1  weight1  weightAdj
20       .       .
25      190      190
26      167      167
27      189      189
28      200      NA
60      300      NA
120     127      127 

Does someone could help me?

>Solution :

We can use dplyr::if_else() or the base r ifelse() function. I assume you mean weight1 < 200 instead of day1 < 200. And why is weightAdj in line 25 and not 190?

library(dplyr)

dat %>% 
  mutate(weightAdj = if_else(day1 > 20 & weight1 < 200, weight1, NA_real_))

#> # A tibble: 7 x 3
#>    day1 weight1 weightAdj
#>   <dbl>   <dbl>     <dbl>
#> 1    20      NA        NA
#> 2    25     190       190
#> 3    26     167       167
#> 4    27     189       189
#> 5    28     200        NA
#> 6    60     300        NA
#> 7   120     127       127

Data from OP:

dat <- tribble(
  ~day1,  ~weight1,
20  ,     NA,
25  ,    190,
26  ,    167,
27  ,    189,
28  ,    200,
60  ,    300,
120 ,    127)

Created on 2023-02-27 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading