Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在r中发出If-Else语句_R_Dataframe_If Statement - Fatal编程技术网

在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"