【发布时间】:2018-05-27 21:12:07
【问题描述】:
我正在尝试模拟每月数据面板,其中一个变量取决于 R 中该变量的滞后值。我的解决方案非常慢。我需要 2545 个人的大约 1000 个样本,多年来每个月都会对他们进行观察,但第一个样本需要我的计算机 8.5 小时来构建。我怎样才能让它更快?
我首先创建一个由不同出生日期、月龄和变量xbsmall 和error 的人组成的不平衡面板,将它们进行比较以确定Outcome。第一个块中的所有代码都只是数据设置。
# Setup:
library(plyr)
# Would like to have 2545 people (nPerson).
#Instead use 4 for testing.
nPerson = 4
# Minimum and maximum possible ages and birth dates
AgeMin = 10
AgeMax = 50
BornMin = 1950
BornMax = 1963
# Person-specific characteristics
ind =
data.frame(
id = 1:nPerson,
BornYear = floor(runif(length(1:nPerson), min=BornMin, max=BornMax+1)),
BornMonth = ceiling(runif(length(1:nPerson), min=0, max=12))
)
# Make an unbalanced panel of people over age 10 up to year 1986
# panel = ddply(ind, ~id, transform, AgeMonths = BornMonth)
panel = ddply(ind, ~id, transform, AgeMonths = (AgeMin*12):((1986-BornYear)*12 + 12-BornMonth))
# Set up some random variables to approximate the data generating process
panel$xbsmall = rnorm(dim(panel)[1], mean=-.3, sd=.45)
# Standard normal error for probit
panel$error = rnorm(dim(panel)[1])
# Placeholders
panel$xb = rep(0, dim(panel)[1])
panel$Outcome = rep(0, dim(panel)[1])
现在我们有了数据,下面是速度较慢的部分(我的计算机上只有 4 次观察大约需要一秒钟,但数千次观察需要几个小时)。每个月,一个人从两个不同的正态分布中获得两次抽奖(xbsmall 和error)(这些都在上面完成),如果xbsmall > error,则Outcome == 1。但是,如果上个月的 Outcome 等于 1,则当 xbsmall + 4.47 > error 时,当前月份的 Outcome 等于 1。我在下面的代码中使用xb = xbsmall+4.47(xb 是概率模型中的“线性预测器”)。为简单起见,我忽略了每个人的第一个月。供您参考,这是模拟一个概率 DGP(但这不是解决计算速度问题所必需的)。
# Outcome == 1 if and only if xb > -error
# The hard part: xb includes information about the previous month's outcome
start_time = Sys.time()
for(i in 1:nPerson){
# Determine the range of monthly ages to loop over for this person
AgeMonthMin = min(panel$AgeMonths[panel$id==i], na.rm=T)
AgeMonthMax = max(panel$AgeMonths[panel$id==i], na.rm=T)
# Loop over the monthly ages for this person and determine the outcome
for(t in (AgeMonthMin+1):AgeMonthMax){
# Indicator for whether Outcome was 1 last month
panel$Outcome1LastMonth[panel$id==i & panel$AgeMonths==t] = panel$Outcome[panel$id==i & panel$AgeMonths==t-1]
# xb = xbsmall + 4.47 if Outcome was 1 last month
# Otherwise, xb = xbsmall
panel$xb[panel$id==i & panel$AgeMonths==t] = with(panel[panel$id==i & panel$AgeMonths==t,], xbsmall + 4.47*Outcome1LastMonth)
# Outcome == 1 if xb > 0
panel$Outcome[panel$id==i & panel$AgeMonths==t] =
ifelse(panel$xb[panel$id==i & panel$AgeMonths==t] > - panel$error[panel$id==i & panel$AgeMonths==t], 1, 0)
}
}
end_time = Sys.time()
end_time - start_time
我对减少计算机时间的想法:
-
cumsum()的东西 - 一些我不知道的精彩面板数据功能
- 找到一种方法让 t 循环通过每个个体的相同起点和终点,然后以某种方式使用
plyr::ddpl()或dplyr::gather_by() - 迭代解决方案:对每个月龄的
Outcome的值(例如模式)进行有根据的猜测,并以某种方式调整与上个月不匹配的值。这在我的实际应用中会更有效,因为 xbsmall 的年龄趋势非常明显。 - 只对较小的样本进行模拟,然后估计样本量对我需要的值的影响(此处未计算回归系数估计值的分布)
【问题讨论】:
标签: r