Stochastic Nonsense

Put something smart here.

Eval in R: Running Code From a String

It’s (very) occasionally quite useful to be able to execute code from a string, similarly to eval in ruby or javascript. You might use this to, eg, read a directory full of csv files and turn each filename into a dataframe containing the corresponding csv. This is difficult to write without such run a string as if it were code functionality because you have no way of knowing the names of the files ahead of time.

In R, you accomplish this via parse and eval. parse turns a string or a file into an expression, and eval evaluates the expression.

Sample:

1
2
3
4
5
6
7
8
9
10
11
12
13
> # set a directory
> setwd( '~/myworkingdirectory' )
> #
> # get a file list and strip off the csv to turn the filenames into variable names
> # note this assumes all files are csvs; you could filter files by the files that match if you needed
> files <- list.files()
> names <- gsub(pattern='\\.csv$', '', files, ignore.case=T)
> 
> for( i in 1:length(names)){
>  a <- paste(names[i], ' <- read.csv( file=\'', files[i], '\', header=T, sep=\',\')', sep='')
>  # print( a )
>  eval(parse( text=a ))
> }