Daniel Gardiner
Daniel Gardiner

Reputation: 1066

Read multiple csv files within a function

I'm trying to read multiple .csv files using a function and have found lots of similar questions/answers but none seem to address my specific issue.

The following code works fine

id=3:5

selected_files=list.files()[id]

for(i in 1:length(id)){
assign(selected_files[i], read.csv(selected_files[i]))
}

However, when putting this code inside a function the code runs but no files are read in

readfiles=function(id){
selected_files=list.files()[id]
for(i in 1:length(id)){
assign(selected_files[i], read.csv(selected_files[i]))
 }
}

Any help?

Upvotes: 1

Views: 439

Answers (1)

symbiotic
symbiotic

Reputation: 373

All of your dataframes are being set within the the function environment, not the global environment. Change your assign() to assign(selected_files[i], read.csv(selected_files[i]), envir = .GlobalEnv)

Upvotes: 2

Related Questions