简体   繁体   English

如何填写R中的空数据帧列表?

[英]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.) (在我的实际数据集中,我有66个位置和300个事件。)

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. 现在,我的任务是预测接下来56天内每个事件在每个地点的事件发生的概率。 In order to do that, I believe that I will need empty data sets for each Location*Event combination. 为此,我相信每个Location * Event组合都需要空数据集。 The code for that is as follows: 其代码如下:

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

dfNames

[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 map function in the purrr package. 我有一个数据帧列表的原因是因为我想在purrr包中使用map函数。 I would like to fill in the names of the locations and events in the Location and Event variables. 我想在LocationEvent变量中填写位置和事件的名称。 Any help is appreciated. 任何帮助表示赞赏。 Thank you! 谢谢!

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. 您实际上应该使用list代替data.frame()list()替换data.frame() list() 。)您的单个“ E1”,“ L1”值将在data.frame中重复56次。

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. 基数R中的Map以及purrr中的大量速记地图功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM