[R] Looping

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Mon Feb 19 06:54:44 CET 2024


Às 03:27 de 19/02/2024, Steven Yen escreveu:
> I need to read csv files repeatedly, named data1.csv, data2.csv,… data24.csv, 24 altogether. That is,
> 
> data<-read.csv(“data1.csv”)
>> data<-read.csv(“data24.csv”)
>> 
> Is there a way to do this in a loop? Thank you.
> 
> Steven from iPhone
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Hello,

Here is a way of reading the files in a *apply loop. The file names are 
created by getting them from file (list.files) or by a string editing 
function (sprintf).


# file_names_vec <- list.files(pattern = "data\\d+\\.csv")
file_names_vec <- sprintf("data%d.csv", 1:24)
data_list <- sapply(file_names_vec, read.csv, simplify = FALSE)

# access the 1st data.frame
data_list[[1L]]
# same as above
data_list[["data1.csv"]]
# same as above
data_list$data1.csv


Hope this helps,

Rui Barradas



-- 
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença de vírus.
www.avg.com



More information about the R-help mailing list