gpt4 book ai didi

r - 尝试使用 R 中的函数在数据框中创建新列

转载 作者:行者123 更新时间:2023-12-04 09:27:03 25 4
gpt4 key购买 nike

我有一个大数据框,我想在 R 中为数据框创建一个新列,但我很挣扎。
我是一个相对的初学者,我将非常感谢您的帮助。
从本质上讲,我希望根据个人的峰值和基线肌酐测量值以及他们是否接受肾脏替代治疗 (RRT),根据以下标准创建一个新的 AKI 阶段列:
阶段 1:峰值 Cr/基线 Cr = 1.5–1.9 或峰值 Cr ≥ 基线 Cr + 26.5mmol/l)
阶段 2:峰值 Cr/基线 Cr = 2.0–2.9
第 3 阶段:峰值 Cr/基线 Cr ≥ 3 或峰值 cr ≥353.6mmol/l 或 RRT 的启动
我的数据看起来像这样,其中有 3 个主要变量。

head(data)
Peak.Creatinine.1 baseline.Cr.within.12.months new.RRT
1 421 82 1
2 659 98 1
3 569 89 1
4 533 113 1
5 533 212 1
6 396 65 1
我想创建一个名为“AKI.stage”的新列,它返回一个数字 0、1、2、3 或 4。
它本质上使用了这个函数:
akistage <- function(peak_cr, bl_cr, rrt=0) {
ratio <- peak_cr / bl_cr
if (rrt == "1"){return(3)}
else if (ratio >= 3){return(3)}
else if (peak_cr > 353.6){return(3)}
else if (ratio > 2 & ratio <3){return(2)}
else if (ratio > 1.5 & ratio <2){return(1)}
else if ((peak_cr >= bl_cr + 26.5)){return(1)}
else {return (0)}
}
该函数在我测试时运行良好,但我似乎无法将其应用于数据框以创建新列。
我已经尝试了多种方式,包括使用应用、映射、变异、转换等,但我似乎无法让它工作。
以下是我的一些失败尝试:
data2$Peak.Creatinine.1 <- as.numeric(data2$Peak.Creatinine.1)
data2$baseline.Cr.within.12.months <- as.numeric(data2$baseline.Cr.within.12.months)
data2$test <- apply(data2, 1, function(x){
ratio <- x[1] / x[2]
peak_cr <- x[1]
bl_cr <- x[2]
rrt <- x[3]
if (rrt == "1"){return(3)}
else if (ratio >= 3){return(3)}
else if (peak_cr > 353.6){return(3)}
else if (ratio > 2 & ratio <3){return(2)}
else if (ratio > 1.5 & ratio <2){return(1)}
else if ((peak_cr >= bl_cr + 26.5)){return(1)}
else {return (0)}
})
但这会返回以下错误消息,尽管是数字类:
Error in x[1]/x[2] : non-numeric argument to binary operator
另一种尝试:
data2 %>% 
mutate(test =
akistage(Peak.Creatinine.1,baseline.Cr.within.12.months,new.RRT))
退货
Warning message:
In if (rrt == "1") { :
the condition has length > 1 and only the first element will be used
我已经尝试了很多其他方式,但我不确定为什么它不起作用。
做起来似乎并不难,如果有人能提出解决方案,我将不胜感激!
非常感谢您的帮助!

最佳答案

以下矢量化函数执行问题所描述的内容。它使用索引向量将返回值分配给之前创建的向量 AKI.stage .

akistage <- function(peak_cr, bl_cr, rrt = 0) {
AKI.stage <- numeric(length(peak_cr))
ratio <- peak_cr / bl_cr
rrt1 <- rrt == 1
i <- findInterval(ratio, c(0, 1.5, 2, 3, Inf))
AKI.stage[rrt1 | i == 4 | peak_cr > 353.6] <- 3
AKI.stage[!rrt1 & i == 3] <- 2
AKI.stage[!rrt1 & i == 2] <- 1
AKI.stage[!rrt1 & i == 1 & peak_cr >= bl_cr + 26.5] <- 1
AKI.stage
}


data %>%
mutate(test = akistage(Peak.Creatinine.1,baseline.Cr.within.12.months,new.RRT))

关于r - 尝试使用 R 中的函数在数据框中创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62969995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com