【发布时间】:2017-07-04 03:32:53
【问题描述】:
所以我有一个面板数据集,并且想为每个 id 的变量 (x) 从一年到另一年的变化/增加分配一些虚拟变量。我写了一个完全符合我要求的函数。不幸的是,它非常慢,因为数据非常大,并且函数必须循环成千上万个 id。
我想知道是否有更有效的方法来生成这些结果,也许是完全避免循环。
值得一提的是,并非所有 id 都在整个时间跨度内被观察到。
AddDummies <- function(ids, startYear = 2003, endYear = 2013){
# Checks for ids over a time span if there has been an increase/change in variable x for a single id from one year to the next
for(i in 1:length(ids)){
cat("Progress: ", round((i/length(ids)), 4)*100, "% \n")
for(k in startYear:endYear){
x.curr <- fullDat[id_d == ids[i] & year == k, x] # x in year k
x.last <- fullDat[id_d == ids[i] & year == k-1, x] # x in year k-1
if(length(x.curr) == 0 | length(x.last) == 0){ # if id has not been in the data the year before or in the current year
# skip and go to next iteration, since change can not be determined
next
} else if(x.curr != x.last){ # if there has been an change in x
fullDat[id_d == ids[i] & year == k, changeDummy := 1] # dummy for change
fullDat[id_d == ids[i] & year == k, changeAbsolute := (x.curr - x.last)] # absolute change
if(x.curr > x.last){
fullDat[id_d == ids[i] & year == k, increase := 1] # dummy for increase
}
if(x.curr == 1 & x.last == 0){
fullDat[id_d == ids[i] & year == k, zeroToOne := 1] # dummy for ids with an increase in x from 0 to 1
}
} else {
next
}
}
}
}
提前致谢
【问题讨论】:
-
能否请您逐步详细说明该函数在我们不破译代码的情况下的作用?
-
您可以查看
dplyr,具体来说,使用group_by(id),然后使用mutate与涉及ifelse' 和lag的操作。
标签: r performance loops data.table