Reputation: 35
I have multiple .csv files in a folder, named as Pt4_1, Pt4_2, Pt5_1, Pt5_2....and so on. Is there a way in R to import a selected files. To my knowledge (definitely very limited) there seems to be a way of importing a .csv files such as:
read.table("Pt4_1.csv", header = TRUE, sep = ",")
However, this dont seem to be of any help to me as I have to import multiple .csv files as a result writing the above said syntax multiple times (tedious).
Can any one suggest a way so I am able to write a loop and call multiple .csv files accordingly? Thank you in advance!!
Upvotes: 2
Views: 1005
Reputation: 886938
If the files are in the working directory and they have a definite pattern, for example, the below code will select files that begin (^
) with Pt
followed by digits (\\d+
), underscore (_
), digits (\\d+
) and the .csv
. Read the files in a "list" using lapply
and read.csv
.
files <- list.files(pattern='^Pt\\d+_\\d+.csv')
lst <- lapply(files, read.csv,header=TRUE)
Another option if the files are very big would be to use fread
from data.table
library(data.table)
lst1 <- lapply(files, fread)
You may be able to create a function to create the pattern.
filePat <- function(d1, d2){
sprintf('Pt%d_%d.csv', d1, d2)
}
filePat(2,3)
#[1] "Pt2_3.csv"
Upvotes: 4