Reputation: 311
I have 100 data set in *.csv format with the same name but different indexes: myarray1, myarray2,..., myarray100. I have written a function to read these data sets and do some stuff but I don't want to run the function 100 times. This is the main part of function:
Myfunc <- function(file){
setwd("C:\\Users\\Desktop\\mydaya")
data.temp1 <- read.csv("C:\\Users\\Desktop\\mydata\\myarray1.csv",header=FALSE)
.......
#core of function
.....
}
is it possible to write a for-loop somehow that runs the function itself 100 times and also change the index of "myarray..." in third command line inside the function at the same time: for example myarray1 in
data.temp <- read.csv("C:\\Users\\Desktop\\mydata\\myarray1.csv",header=FALSE)
becomes myarray2 in second run of the function and so on up to 100 times.
Upvotes: 2
Views: 5776
Reputation: 17189
I think it's not a good idea to use variable names like that. You will be much better of storing the data in the list. I would suggest following methodology
setwd("C:\\Users\\Desktop\\mydata")
files <- dir(pattern = 'myarray.*\\.csv')
dataList <- lapply(files, FUN = Myfunc )
you can then refer to various dataframes by using dataList[[1]] , dataList[[2]] etc. It's much easer to work with list than variables list data.temp1, data.temp2 and so on.
Upvotes: 1
Reputation: 9687
Are you sure you didn't mean read.csv(file, header=FALSE)
?
Then you just can do
lapply(paste0("myarray", 1:100, ".csv"), Myfunc)
Upvotes: 5