States.the.Obvious States.the.Obvious - 1 month ago 6x
R Question

How to fill in a list of empty data frames in R?

I have two locations in a vector:

ListOfLocations <- c("L1", "L2")

I have three events happening at the above two locations in a vector:

ListOfEvents <- c("E1", "E2", "E3")

(In my actual data sets, I have 66 locations and 300 events.)

I have built a model to predict the probabilities of the events occurring at each of those locations with training and test sets with the actual data. Now, my task is to predict probabilities for the occurrence of the events at each of the locations for each event for the next 56 days. In order to do that, I believe that I will need empty data sets for each Location*Event combination. The code for that is as follows:

dfNames <- apply(expand.grid(ListOfLocations, ListOfEvents), 1, function(x) paste0(x[1], x[2]))


[1] "Location1Event1" "Location1Event2" "Location1Event3"
[4] "Location2Event1" "Location2Event2" "Location2Event3"

newData <- setNames(replicate(length(dfNames),
data.frame(Location = character(56),
Event = character(56),
Probs = double(56),
Date = character(56),
DayWeek = integer(56), stringsAsFactors = FALSE), simplify = FALSE), dfNames)

The reason I have a list of data frames is because I'd like to use the
function in the
package. I would like to fill in the names of the locations and events in the
variables. Any help is appreciated. Thank you!

Vlo Vlo

You should really be using list for these kind of things instead of data.frame (simply replace data.frame() with list(). Your single "E1", "L1" values will be repeated 56 times in a data.frame.

Map(f = function(x) data.frame(Location = x[1],
                           Event = x[2],
                           Probs = double(56),
                           Date = character(56),
                           DayWeek = integer(56), stringsAsFactors = FALSE),
    x = data.frame(t(expand.grid(ListOfLocations, ListOfEvents))))

Map in base R works as well as the multitude of shorthand map functions in purrr.