【问题标题】:Printing a function description打印功能描述
【发布时间】:2013-12-05 20:06:45
【问题描述】:

我已经定义了一个函数,比如说f = function(x) {x*x},我想稍后打印这个方程。例如,我希望paste(f) 输出“x*x”。这可能吗?它应该很简单,尽管我愿意接受其他解决方案和建议。

这是我编写的一个简单绘图程序的一部分,它绘制预期线与经验值的关系。程序如下:

generateGraphs <- function() {
  # Vector of running time functions for each implementation running time
  v <- c(function(x){x*x}, function(x){x*x}, function(x){x*log(x)})

  # Vector of file names to be read and graphed
  titles <- c("alpha", "beta", "gamma")

  # Cycle through each problem, reading and graphing the data  
  for (i in 1:3) {
    data <- getData(titles[[i]])
    plotSaveData(data, v[[i]], titles[[i]])
  }
}

plotSaveData <- function(data, expectedOrderEquation, graphTitle) {
  # Define vectors for our x coordinates and two sets of y coordinates 
  empirical <- log(data$Runtime)
  nums <- log(data$N)
  expected <- log(expectedOrderEquation(data$N))

  #   # Start PNG device driver to save output to figure.png
  png(filename=paste0(graphTitle, ".png"), height=295, width=300, bg="white")

  # Compute the largest y value used in the data
  max_y <- max(empirical)

  # Graph empirical running time on log-log scale
  plot(nums, empirical, pch=21, type="p", col="blue", ann=FALSE)

  # Graph expected running time with red line
  lines(nums, expected, col="red", type="l")    

  # Create box around plot
  box()

  # Create a title with a red, bold/italic font
  title(main=paste0("RunningTime: ",graphTitle), col.main="red", font.main=4)

  # Label the x and y axes with dark green text
  title(xlab= "log(array length)", col.lab=rgb(0,0.5,0))
  title(ylab= "log(RunningTime)", col.lab=rgb(0,0.5,0))

  # Create a legend at (.01, max_y) that is slightly smaller 
  # (cex) and uses the same line colors and points used by 
  # the actual plots
  legend(min(nums), max_y, c("Empirical",paste("Expected: ", FUNCTION_HERE!!!)), cex=0.8, col=c("blue","red"), pch=21:22, lty=1:2) # NEED TO PRINT FUNCTION EQUATION HERE

  # Turn off device driver (to flush output to png)
  dev.off()
}

getData <- function(graph.title, summarize = FALSE) {
  ## 'id' is a vector of length 1 indicating the file (or problem)
  ## number. 
  file <- paste0(graph.title,".csv")
  data <- read.csv(file)

  ## 'summarize' is a logical indicating whether a summary of
  ## the data should be printed to the console; the default is
  ## FALSE
  if (summarize) {
    print(summary(data))
  }
  return (data)
}

【问题讨论】:

    标签: string r function


    【解决方案1】:

    可能有更简单的方法,但试试这个:

    > attributes(body(f))$srcref[[2]]
    x*x
    

    【讨论】:

    • 有趣的是,如果你碰巧将你的函数定义为 function(x) x*x 并且没有大括号,这将不起作用。
    • @joran 试试body(f)。我不确定为什么处理方式如此不同。
    • 是的,但在这种情况下,您不能只as.character 结果,因为它实际上是一个调用。
    • @joran 确实如此。烦人,但你可以通过as.character(as.expression(body(f))) 到达那里。
    猜你喜欢
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 2018-07-10
    相关资源
    最近更新 更多