打印功能说明

时间:2013-12-05 20:06:45

标签: string r function

我已经定义了一个函数,比方说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)
}

1 个答案:

答案 0 :(得分:2)

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

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