[R] Looping

Steven Yen @tyen @end|ng |rom ntu@edu@tw
Tue Feb 20 16:24:55 CET 2024


Steven from iPhone

> On Feb 19, 2024, at 4:56 PM, Steven Yen <styen using ntu.edu.tw> wrote:
> 
> Thanks to all. Glad there are many options.
> 
> Steven from iPhone
> 
>>> On Feb 19, 2024, at 1:55 PM, Rui Barradas <ruipbarradas using sapo.pt> wrote:
>>> 
>> À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

	[[alternative HTML version deleted]]



More information about the R-help mailing list