首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用户函数默认参数c(...)之一

用户函数默认参数c(...)之一
EN

Stack Overflow用户
提问于 2020-03-26 21:07:12
回答 1查看 20关注 0票数 0

我正在尝试为我编写的一个函数设置默认值,该函数用于计算要设置的植物之间的距离或在设置间距时每公顷的苗木数量-但是种植系统类型的参数可以接受几个输入中的一个,并将相应地更改该函数所做的操作。如果系统丢失,我希望将系统设置为“正方形”。这就是我到目前为止所尝试的。

代码语言:javascript
复制
plant_spacing <- function(distance, distance_a, distance_b, system=c("square","rectangular"), stems_per_ha, area_m2=10000, output=c("stems per ha","spacing")){

  if(missing(system)){
    system=="square"
  }

  if(output=="stems per ha" & system=="rectangular"){
    area_m2/(dist_a*dist_b)
  }

  if(output=="stems per ha" & system=="square"){
    area_m2/(distance^2)
  }

  if(output=="spacing" & system=="square"){
    sqrt(area_m2/stems_per_ha)
  }
}

它做了正确的事情,但抛出了大量警告:

代码语言:javascript
复制
Warning messages:
1: In if (output == "stems per ha" & system == "rectangular") { :
  the condition has length > 1 and only the first element will be used
2: In if (output == "stems per ha" & system == "square") { :
  the condition has length > 1 and only the first element will be used
3: In if (output == "spacing" & system == "square") { :
  the condition has length > 1 and only the first element will be used

有没有更好的方法来做这件事?提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2020-03-26 21:12:02

R中的每条if语句都必须有一个逻辑值,但是您的比较结果是长度为2的逻辑向量。

代码语言:javascript
复制
system=c("square","rectangular")
output=c("stems per ha","spacing")
output=="stems per ha" & system=="rectangular"
[1] FALSE FALSE

相反,只需在函数中定义默认值即可。然后,如果需要,用户可以更改该值。

代码语言:javascript
复制
plant_spacing <- function(distance, 
                          distance_a, 
                          distance_b, 
                          system="square", 
                          stems_per_ha,
                          area_m2=10000, 
                          output="stems per ha"){

  return(c(system,output))
}
plant_spacing()
[1] "square"       "stems per ha"
plant_spacing(system = "rectangular")
[1] "rectangular"  "stems per ha"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60867986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档