I want to import multiple .DAT
files from a directory and make them as a list elements and then save them as .RDATA
files.
I tried the following code
files <- dir(pattern = "*.DAT")
library(tidyverse)
Data1 <-
files %>%
map(~ read.table(file = ., fill = TRUE))
which works sometimes and fails others. The files are also available on this link. I want to read all files and them save them as .RDATA
with the same names.
Since the data of the link are partly a little bit unclean, I show you the solution of the core problem of your question on the basis of this example data:
We save the data into a sub directory of your working directory named
"test"
.Now we look what's inside
"test"
.Now we import the files in the directory by pattern. I use
rio::import_list
, which nicely imports the files into a list an usesdata.table::fread
inside. But your own code also would work fine.To save them as
.Rdata
we want toassign
names dynamically which we achive with thelist
option withinsave()
.When we list the directory we see that the data was created.
Now let's look whether the object names also were created correctly:
Which is the case.
Add-on option
We alternatively could attempt a more direct approach using
rvest
. First we fetch the data names:and create individual links:
The remainder is basically the same as above:
However, as noted earlier in the introduction, the data are partly a little bit unclean and you probably will have to handle them individually and adapt the code case-wise.