R type conversion [removed]) function()

前端 未结 3 1924
渐次进展
渐次进展 2021-02-15 03:15

I\'ve been trying to write a program in R that implements Newton\'s method. I\'ve been mostly successful, but there are two little snags that have been bothering me. Here\'s m

3条回答
  •  借酒劲吻你
    2021-02-15 03:36

    1. This first problem arises because readline reads in a text string, whereas what you need is an expression. You can use parse() to convert the text string to an expression:

      f <-readline(prompt="Function? ")
      sin(x)
      f
      # [1] "sin(x)"
      
      f <- parse(text = f)
      f
      # expression(sin(x))
      
      g <- D(f, "x")
      g
      # cos(x)
      
    2. To pass in values for the arguments in the function call in the expression (whew!), you can eval() it in an environment containing the supplied values. Nicely, R will allow you to supply those values in a list supplied to the envir= argument of eval():

      > eval(f, envir=list(x=0))
      # [1] 0
      

提交回复
热议问题