R类型转换表达式()函数() [英] R type conversion expression() function()

查看:150
本文介绍了R类型转换表达式()函数()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在R中编写一个实现牛顿方法的程序。我一直都是成功的,但是有两个小小的困扰让我很烦。这是我的代码:

  Newton< --function(f,f。,guess){
#f< readline(prompt =Function?)
#f。 < - readline(prompt =Derivative?)
#guess< - as.numeric(readline(prompt =Guess?))
a < - rep(NA,length =
a [1]< - guess
a [2]< - a [1] - f(a [1])/ f。(a [1])$ ​​b $ b for 2:length(a)){
if(a [i] == a [i-1]){
break
}
else {
a [i +1]< - a [i] - f(a [i])/ f。(a [i])
}
}
a < - a [complete.cases a)]
return(a)
}




  1. 如果我尝试使用 f f。 code> readline()提示用户输入。我得到错误牛顿()中的错误:找不到功能f。但是,如果我注释掉readline(如上),定义 f f。事先,一切都正常。


  2. 我一直在试图让R计算衍生物的功能。问题是R可以使用符号衍生物的类对象是 expression(),但是我想使用函数() 并让它给我一个 function()。简而言之,我在 expression() function()之间的类型转换有困难。


我有一个丑陋但有效的解决方案,从 function() expression()。给定函数f, D(body(f)[[2]],x)将给出 f 。但是,这个输出是一个表达式(),我无法将其重新转换为 function()。我需要使用 eval()还是什么?我尝试了子集,但无济于事。例如:

  g<  - 表达式(sin(x))
g [[1]]
sin(x)
f < - function(x){g [[1]]}
f(0)
sin(x)

当我想要的是f(0)= 0,因为sin(0)= 0。



编辑:感谢所有!这是我的新代码:

  Newton< -function(f,f。,guess){
g < (prompt =Function?)
g< -parse(text = g)
g。< -D(g,x)
f < eval(g [[1]])}
f。< -function(x){eval(g。)}
guess< -as.numeric(readline(prompt =Guess? )
a< -rep(NA,length = 1000)
a [1]< -guess
a [2]< -a [1] -f(a [1])/ f(a [1])$ ​​b $ b for(i in 2:length(a)){
if(a [i] == a [i-1]){break
} else {
a [i + 1]< -a [i] -f(a [i])/ f。(a [i])
}
}
a< ; -a [complete.cases(a)]
#a< -a [1:(length(a)-1)]
return(a)
}


解决方案


  1. code> readline 读入一个文本字符串,而你需要的是一个表达式。您可以使用 parse()将文本字符串转换为表达式:

      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. 传递函数调用中参数的值表达式(whew!),您可以在包含提供的值的环境中 eval()。很好,R将允许您在提供给 envir = 参数 eval()的列表中提供这些值:

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



    1. 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 my code:

      Newton<-function(f,f.,guess){
          #f <- readline(prompt="Function? ")
          #f. <- readline(prompt="Derivative? ")
          #guess <- as.numeric(readline(prompt="Guess? "))
          a <- rep(NA, length=1000)
          a[1] <- guess
          a[2] <- a[1] - f(a[1]) / f.(a[1])
          for(i in 2:length(a)){
              if(a[i] == a[i-1]){
                 break
              } 
              else{
                 a[i+1] <- a[i] - f(a[i]) / f.(a[i])
              }
          }   
          a <- a[complete.cases(a)]
          return(a)
      }
      

      1. I can't get R to recognize the functions f and f. if I try using readline() to prompt for user input. I get the error "Error in Newton() : could not find function "f."" However, if I comment out the readlines (as above), define f and f. beforehand, then everything works fine.

      2. I've been trying to make R calculate the derivative of a function. The problem is that the class object with which R can take symbolic derivatives is expression(), but I want to take the derivative of a function() and have it give me a function(). In short, I'm having trouble with type conversion between expression() and function().

      I have an ugly but effective solution for going from function() to expression(). Given a function f, D(body(f)[[2]],"x") will give the derivative of f. However, this output is an expression(), and I haven't been able to turn it back into a function(). Do I need to use eval() or something? I've tried subsetting, but to no avail. For instance:

      g <- expression(sin(x))
      g[[1]]
      sin(x)
      f <- function(x){g[[1]]}
      f(0)
      sin(x)
      

      when what I want is f(0) = 0 since sin(0) = 0.

      EDIT: Thanks all! Here's my new code:

      Newton<-function(f,f.,guess){
          g<-readline(prompt="Function? ")
          g<-parse(text=g)
          g.<-D(g,"x")
          f<-function(x){eval(g[[1]])}
          f.<-function(x){eval(g.)}
          guess<-as.numeric(readline(prompt="Guess? "))
          a<-rep(NA, length=1000)
          a[1]<-guess
          a[2]<-a[1]-f(a[1])/f.(a[1])
          for(i in 2:length(a)){
              if(a[i]==a[i-1]){break
              }else{
              a[i+1]<-a[i]-f(a[i])/f.(a[i])
              }
          }   
      a<-a[complete.cases(a)]
      #a<-a[1:(length(a)-1)]
      return(a)
      }
      

      解决方案

      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
        

      这篇关于R类型转换表达式()函数()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆