简体   繁体   English

为什么当我尝试将参数传递给if函数时R生成错误

[英]why R generating error when i try to pass argument to the if function

here i am giving the code 在这里我给的代码

#my user defined function
my.display<-function(x,display=TRUE,type="hist",prob=TRUE)
{

  if(display=TRUE)
print("1")

  else hist(x)

  if(type=hist) hist(x) elseif(type=density) plot(density(x))
  cat("Please specify type as either hist or density")

  if(prob=TRUE) hist(x,freq=TRUE) else hist(x,freq=TRUE)
  }

the error r shows is when it passes to the if(display=TRUE), I believe the expression is wrong or something. r所显示的错误是当它传递给if(display = TRUE)时,我认为该表达式有误。 if the display=TRUE argument then it should print 1 else generate a histogram of the vector x. 如果display = TRUE自变量,则应打印1,否则生成向量x的直方图。

if(type=hist) also showing error . if(type=hist)也显示error。 someone please help. 有人请帮忙。

= acts as assign operator same as <- operator in R =充当分配运算符,与R中的<-运算符相同

while == is a logical operator. ==是逻辑运算符。

So you should use if(display == TRUE) . 因此,您应该使用if(display == TRUE) You might also want to add some {} in your if-else structures for readability. 您可能还希望在if-else结构中添加一些{}以提高可读性。

Try this code for second doubt 尝试使用此代码来解决第二个疑问

updated: 更新:

my.display<-function(x,display,type,prob=TRUE)
{if(display==TRUE){
    print("1")
  }
  else 
  if(type=="hist") {hist(x)}
  else
    if(type=="density") {plot(density(x))}
  else
  cat("Please specify type as either hist or density")
  if(prob==TRUE){ hist(x,freq=TRUE)}
  else 
    hist(x,freq=TRUE)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM