来自多个if/else if语句的多个动作-R [英] Multiple actions from multiple if / else if statements - R
问题描述
我是R的新手,并且遇到了在数据帧内正确填充一列数据的问题.我正在使用一系列if/else if语句基于另一列(P_Value)填充两列(P_Score和P_Class).
I'm new to R and am experiencing a problem properly populating a column of data within a data frame. I'm populating two columns (P_Score and P_Class) based on another column (P_Value) using a series of if / else if statements.
i<- 0
nr<- nrow(myData)
while(i<nr){
i<-1+i
if(toString(myData$P_Value[i])=="NA"){ myData$P_Score[i] <- myData$P_Value[i]
} else if (as.numeric(toString(myData$P_Value[i]))<5){
myData$P_Score[i] <- 1; myData$P_Class[i] <- "Minimal Depression";
} else if (as.numeric(toString(myData$P_Value[i]))<10){
myData$P_Score[i] <- 2; myData$P_Class[i] <- "Mild Depression";
} else if (as.numeric(toString(myData$P_Value[i]))<15){
myData$P_Score[i] <- 3; myData$P_Class[i] <- "Moderate Depression";
} else if (as.numeric(toString(myData$P_Value[i]))<20){
myData$P_Score[i] <- 4; myData$P_Class[i] <- "Moderate-Severe Depression";
} else
myData$P_Score[i] <- 5; myData$P_Class[i] <- "Severe Depression";
}
但是,这并没有给我我想要的结果,相反,我想到了:
However, this is not giving me my desired result, and instead I wind up with this:
P_Value P_Score P_Class
4 1 Severe Depression
25 5 Severe Depression
8 2 Severe Depression
13 3 Severe Depression
17 4 Severe Depression
1 1 Severe Depression
12 3 Severe Depression
因此P_Score可以很好地填充,但是P_Class始终默认为严重抑郁".我必须在执行基于if条件的多个语句时遇到一些问题,但是我无法弄清楚我在做什么错.我在其他地方读过,只要您在分号后都加分号即可,但这显然行不通.
So the P_Score is populating just fine, but the P_Class is always defaulting to "Severe Depression". I must be having some issue executing multiple statements based off of 1 if condition, but I can't figure out what I'm doing wrong. I have read elsewhere as long as you put semicolons after the statements both should work, but that's clearly not working.
我还尝试过将命令间隔开:
I have also tried spacing out the commands like this:
} else if (as.numeric(toString(myData$P_Value[i]))<5){
myData$P_Score[i] <- 1
myData$P_Class[i] <- "Minimal Depression"
但这似乎也不起作用.请帮忙!
But that does not seem to work either. Please help!
推荐答案
R为此提供了一个功能,不需要任何循环.请阅读?cut
:
R has a function for this, there is no need for any loops. Please read ?cut
:
设置示例
myData
# P_Value
# 1 4
# 2 25
# 3 8
# 4 13
# 5 17
# 6 1
# 7 12
# 8 NA
grps <- cut(myData$P_Value,
breaks=c(-Inf, 5, 10, 15, 20, Inf),
labels=c("Min Dep", "Mild Dep", "Mod Dep", "Mod-Sev Dep", "Sev Dep"))
创建了分组后,我们可以从中创建一个得分和类别"列
With the groups created, we can make a Score and Class column from it
myData$P_Score <- as.numeric(grps)
myData$P_Class <- grps
myData
# P_Value P_Score P_Class
# 1 4 1 Min Dep
# 2 25 5 Sev Dep
# 3 8 2 Mild Dep
# 4 13 3 Mod Dep
# 5 17 4 Mod-Sev Dep
# 6 1 1 Min Dep
# 7 12 3 Mod Dep
# 8 NA NA <NA>
这篇关于来自多个if/else if语句的多个动作-R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!