This question is somewhat of a continuation of a previous question I asked Combining data based on user input in R. It was recommended to store my data in lists rather than as individual items in the global environment. Therefore I am attempting to import all similar file types (e.g. .csv) into a list of lists. Each nested list represents one of multiple time series .csv files. This currently works using the following code:
ImportData <- function(mypattern,...)
{
mypattern <- readline(prompt = "Enter File Type:")
temp <- list.files(".", pattern=mypattern)
myfiles <- lapply(temp, fread, skip = 1)
names(myfiles) <- gsub("-.*", "", temp)
header <- c("index","DateTime", "Voltage")
myfiles <<- lapply(myfiles, setNames, header)
}
ImportData()
The next step is to combine lists of time series data with similar names that represent data from the same site. After running the above function myfiles
contains lists with names such as ASW1.csv, ASW1_10Sept.csv, ASW1_2017, as well as others with different abbreviations (e.g. CSW). My goal with the below function is to prompt the user to input a site name (e.g. ASW1) and for every list within the myfiles
list with a name containing ASW1 to be combined and sorted by date into a new list called ASW1 within myfiles
. Then the user can call all the data from a particular site.
CombineData <- function()
{
Site <- invisible(readline(prompt = "Enter Site Name:"))
myfiles[[Site]] <<- rbindlist(mget(apropos(Site), inherits = TRUE))
}
CombineData()
The issue I am having is when running CombineData
an empty list is added to myfiles
rather than one that contains all the data from any list with the name provided in Site
. I can manually combine the lists:
ASW1 <- myfiles[c(1,2,3,4)]
ASW1 <- rbindlist(ASW1)
but my goal is to make this process as automated as possible. In a previous version of my code I used the following to grab everything containing a particular name do.call(rbind, mget(ls(pattern = "^ASW1")))
but clearly there must be something different when working with lists.