在r中发出If-Else语句
我试图创建一个函数,该函数将从数据帧中的三个不同列返回“正”或“负” 这是我的代码:在r中发出If-Else语句,r,dataframe,if-statement,R,Dataframe,If Statement,我试图创建一个函数,该函数将从数据帧中的三个不同列返回“正”或“负” 这是我的代码: BeforeDep <- BeforeWar_HaveDepression BeforeAnx <- BeforeWar_HaveAnxiety BeforePTSD <- BeforeWar_HavePTSD BeforeWar_MentalHealth <- function(BeforeDep, BeforeAnx, BeforePTSD) if (BeforeDep ==
BeforeDep <- BeforeWar_HaveDepression
BeforeAnx <- BeforeWar_HaveAnxiety
BeforePTSD <- BeforeWar_HavePTSD
BeforeWar_MentalHealth <- function(BeforeDep, BeforeAnx, BeforePTSD)
if (BeforeDep == 1) {
print ("Positive")
} else if (BeforeAnx == 1) {
print ("Positive")
} else if (BeforePTSD == 1 ) {
print ("Positive")
} else {
print ("Negative")
}
BeforeDep是否使用参数调用函数?我尝试了你的功能,它工作了。见下文
BeforeDep <- 1
BeforeAnx <- 1
BeforePTSD <- 1
BeforeWar_MentalHealth <- function(BeforeDep, BeforeAnx, BeforePTSD)
if (BeforeDep == 1) {
print ("Positive")
} else if (BeforeAnx == 1) {
print ("Positive")
} else if (BeforePTSD == 1 ) {
print ("Positive")
} else {
print ("Negative")
}
# Calling the function
BeforeWar_MentalHealth(0,0,0)
哪一个是错误?如果在向量上运行此操作,则需要使用向量化的ifelse
。printt()
ing不同于return()
ing。很少需要在函数内部打印,如果您想告诉用户一些事情,通常最好使用message()
或warning()
。如果要给它们一个R对象(如字符串“Negative”
),请使用return()
。
> BeforeWar_MentalHealth(1,1,1)
[1] "Positive"
> BeforeWar_MentalHealth(0,1,1)
[1] "Positive"
> BeforeWar_MentalHealth(0,0,0)
[1] "Negative"