I'm new to coding in R and am having a difficult time coding the following equation
142 x (Scr/A)^B x 0.9938^age x (1.012 if female)
Female
- Scr <=0.7; A = 0.7, B = -0.241
- Scr >0.7; A = 0.7, B = -1.2
Male
- Scr <=0.9; A = 0.9, B = -0.302
- Scr >0.9; A = 0.9, B = -1.2
(There is an existing R package for the old version of this equation, but not this updated one).
Could someone help me with the code? Having a hard time figuring out how to create a new variable (eGFR) with values calculated from this equation. The components A and B of the equation depend on 2 categories of variable Scr (serum creatinine) and on gender (M/F). Thanks!
wave1.data$baseline.egfr <- (if(wave1.data$Sex=="Male") {M1 <- wave1.data$Creatinine >= 0.9
M2 <- wave1.data$Creatinine < 0.9
eGFR <- (142*(wave1.data$Creatinine/A1)^-0.302*(0.9938^wave1.data$Age))
eGFR <- (142*(wave1.data$Creatinine/A2)^-1.2*(0.9938^wave1.data$Age))}
else if(wave1.data$Sex=="Female")
{F1 <- wave1.data$Creatinine >= 0.7
F2 <- wave1.data$Creatinine < 0.7
eGFR <- (142*(wave1.data$Creatinine/A1)^-0.241*(0.9938^wave1.data$Age))
eGFR <- (142*(wave1.data$Creatinine/A2)^-1.2*(0.9938^wave1.data$Age))})
CodePudding user response:
I hope this function well represents the formula for individual case:
ckdi <- function(sex_i, scr, age){
female_scr <- c(0, 0.7)
male_scr <- c(0, 0.9)
female_A <- c(0.7, 0.7)
female_B <- c(-0.241, -1.2)
male_A <- c(0.9, 0.9)
male_B <- c(-0.302, -1.2)
if(sex_i == "F"){
scrid <- findInterval(scr, female_scr, left.open = TRUE)
A <- female_A[scrid]
B <- female_B[scrid]
k <- 1.012
}
if(sex_i == "M"){
scrid <- findInterval(scr, male_scr, left.open = TRUE)
A <- male_A[scrid]
B <- male_B[scrid]
k<- 1.000
}
result_i <- 142*(scr/A)^B * 0.9938^age * k
return(result_i)
}
To apply to multiple data, mapply
can be used. For example:
set.seed(1)
scr_all <- runif(3)
age_all <- runif(3, 30,50)
sex_all <- c("F", "M", "F")
mapply(ckdi, sex_all, scr_all, age_all)
# F M F
#134.5373 150.0365 111.9148
CodePudding user response:
You can do:
eGFR <- function(Scr, age, sex) {
sex <- tolower(sex)
A <- ifelse(sex == "female", 0.7, 0.9)
B <- ifelse(Scr > A, -1.2,
ifelse(sex == "female", -0.241, -0.302))
mult <- ifelse(sex == "female", 1.012, 1)
round(142 * (Scr/A)^B * 0.9938^age * mult)
}
eGFR(0.6, 35, "male")
#> [1] 129
eGFR(0.75, 35, "Male")
#> [1] 121
eGFR(0.8, 80, "female")
#> [1] 74
eGFR(Scr = c(0.6, 0.8), age = c(35, 80), sex = c("male", "female"))
#> [1] 129 74
Created on 2022-04-18 by the reprex package (v2.0.1)