我是R的新手,我只是想写一个简单的函数,用户将输入右边三角形的2个已知边,然后输出将是第三边的长度。我有一个“修复”工作,但它是一个胶带解决方案。这个想法是用户可以调用我的函数,名为pythag。我希望他们能够输入pythag(3,b,5)来输入值。这将告诉程序三角形的一条腿是长度3,斜边是长度5,解决另一条腿,腿b。但我唯一能让它发挥作用的方法是用户输入pythag(3,“b”,5)。这是代码:
pythag <- function(a, b, c) {
if (a %in% "a") {
answer <- sqrt(c^2 - b^2)
} else if ( b %in% "b") {
answer <- sqrt(c^2 - a^2)
} else if (c %in% "c") {
answer <- sqrt(a^2 + b^2)
}
answer }
如果我删除代码中的“”,使其表示为(%a%),则不起作用。任何帮助,将不胜感激。我也试过(a == a)和(a = a)。
答案 0 :(得分:1)
我不确定你为什么要这样设计你的功能,因为三角形边的标签很大程度上是任意的。但如果你坚持,我会这样做:
pythag <- function(A=NA, B=NA, C=NA) {
# want to check inputs
inputs <- c(A, B, C)
if (sum(is.na(inputs)) != 1)
stop("Exactly two inputs are required!")
if (is.na(A)) return(sqrt(C^2 - B^2))
if (is.na(B)) return(sqrt(C^2 - A^2))
if (is.na(C)) return(sqrt(A^2 + B^2))
}
pythag(A=3, B=4)
[1] 5
pythag(A=3, C=5)
[1] 4
pythag(B=4, C=5)
[1] 3
当然,这个功能仍然不是很好,因为它不能从不良输入中“免疫”。但它通常适合你。
答案 1 :(得分:1)
此答案取决于您的用户命名已知输入。然后它会吐出未知输入的名称和值。
# Create the Pythageorean Theorem function
# A squared + B squared = C squared
PythagoreanTheorem <- function( a = NULL, b = NULL, c = NULL ){
# Takes in two inputs and calculates
# the missing parameter's value
# Args: two numeric values
# Stop messages
if( !is.null( x = a ) &&
!is.null( x = b ) &&
!is.null( x = c ) ){
stop( "All three arguments cannot be used. Use two.")
}
if( !is.numeric( x = a ) && !is.null( x = a ) |
!is.numeric( x = b ) && !is.null( x = b ) |
!is.numeric( x = c ) && !is.null( x = c ) ){
stop( "Ensure both inputs are numeric.")
}
if( !is.null( a ) && !is.null( b ) ){
return(
setNames(
object = sqrt( x = c( a^2 + b^2 ) )
, nm = "c"
)
)
} else if( !is.null( a ) && !is.null( c ) ){
return(
setNames(
object = sqrt( x = c( a^2 + c^2 ) )
, nm = "b"
)
)
} else if( !is.null( b ) && !is.null( c ) ){
return(
setNames(
object = sqrt( x = c( b^2 + c^2 ) )
, nm = "a"
)
)
}
} # end of PythagoreanTheorem() function
# test PythagoreanTheorem() function
PythagoreanTheorem( c = 3, a = 4 )
# b
# 5
class( x = PythagoreanTheorem( c = 3, a = 4 ) )
# [1] "numeric"
PythagoreanTheorem( a = 2, b = 5, c = 6)
# Error in PythagoreanTheorem(a = 2, b = 5, c = 6) :
# All three arguments cannot be used. Use two.
# end of script #
答案 2 :(得分:0)
尝试使用稍微不同的用户界面:
pythag <- function(a = 0, b = 0, c = 0) {
stopifnot(is.numeric(a), is.numeric(b), is.numeric(c), (a!=0) + (b!=0) + (c!=0) == 2)
if (c == 0) sqrt(a^2 + b^2) else sqrt(c^2 - a^2 - b^2)
}
# tests
pythag(a = 3, c = 5)
## [1] 4
pythag(3,,5) # same
## [1] 4
pythag(a = 4, b = 3)
## [1] 5
pythag(4, 3) # same
## [1] 5
pythag(3, "X")
## Error: is.numeric(b) is not TRUE
pythag(1)
## Error: (a != 0) + (b != 0) + (c != 0) == 2 is not TRUE
pythag(1, 2, 3)
## Error: (a != 0) + (b != 0) + (c != 0) == 2 is not TRUE