Reputation: 851
Context:
I'm trying to set up some mock data testing and I have saved some mock data down as csvs in a directory called 'test/'.
Each file relates to a get_data type function e.g. the mock data for get_energy() is stored as test/get_energy.csv.
I'd like to use list.files() to assign functions to my environment that read the csv.
files<-list.files('test/')
for (name in substr(files,1,nchar(files)-4)){
assign(name,function(){read.csv(eval(parse(text=paste0('test/',name,'.csv')))) })
}
but when I try and see the source code for the function get_energy by running
get_energy
it returns
function(){read.csv(eval(parse(text=paste0('test/',name,'.csv'))))}
whereas I need it to evaluate the string expression so that it returns
function(){read.csv('test/get_energy.csv')}
Upvotes: 0
Views: 31
Reputation: 124213
Put the whole function definition in the string like so:
files <- list.files("test/", pattern = 'csv$')
for (name in substr(files,1,nchar(files)-4)) {
assign(name, eval(parse(text = paste0('function(){ read.csv(', '"test/', name, '.csv', '")}'))))
}
Upvotes: 1