我正在尝试为我编写的一个函数设置默认值,该函数用于计算要设置的植物之间的距离或在设置间距时每公顷的苗木数量-但是种植系统类型的参数可以接受几个输入中的一个,并将相应地更改该函数所做的操作。如果系统丢失,我希望将系统设置为“正方形”。这就是我到目前为止所尝试的。
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)
}
}它做了正确的事情,但抛出了大量警告:
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有没有更好的方法来做这件事?提前谢谢。
发布于 2020-03-26 21:12:02
R中的每条if语句都必须有一个逻辑值,但是您的比较结果是长度为2的逻辑向量。
system=c("square","rectangular")
output=c("stems per ha","spacing")
output=="stems per ha" & system=="rectangular"
[1] FALSE FALSE相反,只需在函数中定义默认值即可。然后,如果需要,用户可以更改该值。
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"https://stackoverflow.com/questions/60867986
复制相似问题