The goal of this tutorial is to learn how to read a csv without typing the name into R. We will ask which files ara available in the working directory and open the file we want to use.
# We can list all files that exist in our working directory
list.files()
## [1] "iris.csv" "prediction.csv"
## [3] "transactions.csv" "UsefulConsoleFunctions.html"
## [5] "UsefulConsoleFunctions.Rmd"
# Now we can filter only the csv files existing in our working directory
list.files(pattern="*.csv")
## [1] "iris.csv" "prediction.csv" "transactions.csv"
# Finally we can store this information in a variable
filenames <- list.files(pattern="*.csv")
# We can see all the filenames
filenames
## [1] "iris.csv" "prediction.csv" "transactions.csv"
# And read the selected file
head(read.csv(filenames[1], header = TRUE, sep = ","))
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
In this tutorial we have learnt how to read files using the list of filenames.