简体   繁体   中英

Running a function multiple times in R

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.

Are you sure you didn't mean read.csv(file, header=FALSE) ?

Then you just can do

lapply(paste0("myarray", 1:100, ".csv"), Myfunc)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM