简体   繁体   English

在r中,如何使函数将特定字母识别为我要解决的未知值?

[英]In r, how do I make my function recognize a specific letter as the unknown value that I want it to solve for?

I am new to R and I am just trying to write a simple function where the user will input 2 known sides of a right triangle and then the output will be the length of the third side. 我是R的新手,我只是想编写一个简单的函数,用户将输入直角三角形的2个已知边,然后输出为第三边的长度。 I have it working with a "fix" but it's a duct tape solution. 我使用“修复”功能,但这是胶带解决方案。 The idea is that the user will be able to call on my function, named pythag. 这个想法是用户可以调用名为pythag的函数。 I want them to be able to enter in values by typing pythag(3,b,5). 我希望他们能够通过键入pythag(3,b,5)输入值。 This would tell the program that one leg of the triangle is length 3, the hypotenuse is length 5, solve for the other leg, leg b. 这将告诉程序三角形的一条边长为3,斜边为边长5,求解另一条边,即边b。 But the only way I've gotten it to work is if the user types in pythag(3, "b", 5). 但是,使它起作用的唯一方法是用户键入pythag(3,“ b”,5)。 Here is the code: 这是代码:

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 }

If I take away the "" in the code so that it is stated as (a %in% a), it doesn't work. 如果我删除代码中的“”,使其表示为(a%in%a),则它不起作用。 Any help would be appreciated. 任何帮助,将不胜感激。 I've also tried (a==a) and (a=a). 我也尝试过(a == a)和(a = a)。

I am not sure why you would want to design your function this way, since the labels of triangle sides are largely arbitrary. 我不确定为什么要这样设计函数,因为三角形边的标签在很大程度上是任意的。 But if you insist, I would approach it this way: 但是,如果您坚持,我会这样处理:

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

Of course, this function is still not great, since it is not "immune" from bad inputs. 当然,该功能仍然不是很好,因为它不能从不良输入中“免疫”。 But it should generally work for you. 但它通常应该为您工作。

This answer relies on your users naming the known inputs. 此答案取决于您的用户命名已知输入。 It then spits out the name and value of the unknown input. 然后,它吐出未知输入的名称和值。

# 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 #

Try this with a slightly different user interface: 使用稍微不同的用户界面尝试以下操作:

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

暂无
暂无

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

相关问题 如何在R中创建特定功能以模拟生物学情况 - How do I make a specific function in R to simulate a biological situation 如何让 R 识别来自目录中另一个依赖项的 function? - How do I make R recognize a function that comes from another dependency within the directory? 我想在 R 中为特定值创建四分位数。 我想按类别创建四分位数。 我怎样才能做到这一点? - I want to create quartiles in R for a specific value. I want to create the quartiles category-wise. How can I do that? 如何使用三列在 R 中制作堆叠条形图,我想使用 barplot() 函数 - How do I make stacked barplot in R utilising three columns, I want to use the barplot() function R - 我可以让 R 识别列名是否是值的一部分吗? - R - Can I make R recognize if name of column is part of value? R 采样字母(字母)时如何检查下一个字母是否比前一个字母更大? - R when sampling letters (LETTERS) how do I check if the next letter is a greater letter value then the previous one? 如何在 R 的 sum 函数中分离我想要的对象? - How do I separate the object I want in a sum function in R? 我如何在R中制作这个function? - How do I make this function in R? 如何在我想用来进行连接的 R function 中传递参数 - How to pass an argument in a R function that I want to use to make a join 我要如何编写基于行首字母运行的 function? - How do I want to write a function that will run based on the first letter of a line?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM