我有一个 tibble 来计算以下列名称的格拉斯哥昏迷量表:“gcs_eye”“gcs_motor”“gcs_verbal”“gcs_total” 前三列是由复选框调查生成的,因此它们要么为空,要么具有可预测的字符串。 GCS 总计为空或数字。我的目标是创建一个新列,如果存在,则从 GCS 总计列中获取数字,或者使用其他三列中的测试条目来计算 GCS。
为此,我使用下面的代码。然而,这只是结转 gcs_total 分数,而不是从文本中计算 GCS(仅转储 NA)。有人可以帮我弄清楚我做错了什么吗?另外,有人可以告诉我什么时候我需要我们 + 在缩进代码行的末尾开始吗? 谢谢你!我还在下面放了一些样本数据。
##Calculate GCS
GCS <- function(total, eye, motor, verbal){
#return GCS total if calculated previously
if (is.numeric(total)) {
return(total)
} else {
#Set baseline GCS
GCS <- NA
}
if (eye == "Spontaneous"){
GCS <- 6
} else if (eye == "To voice"){
GCS <- 5
} else if (eye == "To pain"){
GCS <- 4
} else if (eye == "None"){
GCS <- 3 #None adds no points
} else {
GCS <- GCS
}
if (verbal == "Oriented"){
GCS <- GCS +4
} else if (eye == "Confused"){
GCS <- GCS +3
} else if (eye == "Inappropriate"){
GCS <- GCS +2
} else if (eye == "Incomprehensible"){
GCS <- GCS +1
} else {
GCS <- GCS #None adds no points
}
if (motor == "Obeys commands"){
GCS <- GCS +5
} else if (motor == "Localizes to pain"){
GCS <- GCS +4
} else if (motor == "Flexion withdrawal"){
GCS <- GCS +3
} else if (motor== "Abnormal flexion"){
GCS <- GCS +2
} else if (motor== "Abnormal extension"){
GCS <- GCS +1
} else {
GCS <- GCS #None adds no points
}
return(GCS)
}
data$GCS <- mapply(FUN = GCS, total = data$gcs_total, eye = data$gcs_eye,
motor = data$gcs_motor, verbal = data$gcs_verbal)
这里是一些示例数据:
data$gcs_eye <- c("","","","Spontaneous","Spontaneous","To voice")
data$gcs_motor <- c("","","","Obeys commands","Localizes to pain","
Flexion withdrawal")
data$gcs_verbal <- c("","","","Confused","Incomprehensible","None")
data$gcs_verbal <- c(NA, 13, 15, 14, NA, NA)
(如果我运行当前代码,它应该输出 c(NA, 13, 15, 14, NA, NA)
这对你有用吗:
如果是,那你只是打错了
eye == "Confused"...
应该是
Verbal == "Confused"...
等
我认为@Gregor Thomas 已经在评论中解决了这个问题:
GCS <- function(total, eye, motor, verbal){
#return GCS total if calculated previously
if (is.numeric(total)) {
return(total)
} else {
#Set baseline GCS
GCS <- NA
}
if (eye == "Spontaneous"){
GCS <- 6
} else if (eye == "To voice"){
GCS <- 5
} else if (eye == "To pain"){
GCS <- 4
} else if (eye == "None"){
GCS <- 3 #None adds no points
} else {
GCS <- GCS
}
if (verbal == "Oriented"){
GCS <- GCS +4
} else if (verbal == "Confused"){
GCS <- GCS +3
} else if (verbal == "Inappropriate"){
GCS <- GCS +2
} else if (verbal == "Incomprehensible"){
GCS <- GCS +1
} else {
GCS <- GCS #None adds no points
}
if (motor == "Obeys commands"){
GCS <- GCS +5
} else if (motor == "Localizes to pain"){
GCS <- GCS +4
} else if (motor == "Flexion withdrawal"){
GCS <- GCS +3
} else if (motor== "Abnormal flexion"){
GCS <- GCS +2
} else if (motor== "Abnormal extension"){
GCS <- GCS +1
} else {
GCS <- GCS #None adds no points
}
return(GCS)
}