How create a IF and then function in R

Advertisements

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)

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)

Leave a Reply Cancel reply