s-news
[Top] [All Lists]

the use of eval and parse

To: s-news@lists.biostat.wustl.edu
Subject: the use of eval and parse
From: "Colin Maurice" <colinsplus@hotmail.com>
Date: Mon, 27 Feb 2006 11:12:24 -0500

Dear members,

I was wondering why so many people use the "eval" and "parse" commands together along with the "paste" command, even when there doesn't appear to be any obvious reason why. For instance, I found the following code in an Splus Library:

table.to.data.frame <- function(TheTable, DataName, TheList)
{
#
#  convert a table to a data.frame containing the same information
#
#  TheTable contains the table
#  DataName is a string to head the data column
#  TheList is a list of strings being the headings for the dimensions
#     of the table
#
  TheData <- as.vector(TheTable)
  N <- length(TheData)
  eval(parse(text = paste("TheDataFrame <- data.frame(", DataName,
     " = TheData, row.names = 1:N)", sep = "")))
  DN <- dimnames(TheTable)
  K <- length(DN)
  if(K != length(TheList))
  {
     print("List is wrong length")
     return(NA)
  }
  r1 <- 1
  r2 <- N
  for(k in 1:K)
  {
     len <- length(DN[[k]])
     r2 <- r2/len
     eval(parse(text = paste("TheDataFrame$", TheList[k],
        " <- rep(rep(DN[[k]], rep(r1, len)), r2)", sep = "")))
     r1 <- r1 * len
  }
  TheDataFrame
}

But I don't know why

eval(parse(text = paste("TheDataFrame <- data.frame(", DataName,
     " = TheData, row.names = 1:N)", sep = "")))

couldn't have been replaced with

TheDataFrame <- data.frame(DataName= TheData, row.names = 1:N)

Can someone explain why it is sometimes better to use "eval" and "parse" rather than the standard why of assigning objects.

Any help is much appreciated.

Colin

_________________________________________________________________
Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/


<Prev in Thread] Current Thread [Next in Thread>