我目前正在寻找一种方法来创建一组虚拟变量来指示面板中的时间事件。我明确地试图制作虚拟变量来指示事件发生前20年和事件发生后20年的事件,例如: 20年来战争对贸易的影响。我想为dyads中的每个parnter编码这个虚拟对象。怎么可能优雅地编程这些事件假人?我很感激你的帮助:)
iso_o iso_d year mid_o mid_d
ABW AFG 1980 0 1
ABW AFG 1981 0 1
ABW AFG 1982 0 1
ABW AFG 1983 0 2
ABW AFG 1984 0 1
ABW AFG 1985 0 1
ABW AFG 1986 0 1
ABW AFG 1987 0 1
ABW AFG 1988 0 0
ABW AFG 1989 0 1
所以,这就是我想去的地方:
iso_o iso_d year mid_o mid_d mid_o_t-20 mid_o_t-19 mid o_t-18 .... mid_d_t-20
ABW AFG 1980 0 1 0 0 0
ABW AFG 1981 0 1 0 0 0
ABW AFG 1982 0 1 0 0 0
ABW AFG 1983 0 2 0 0 0
ABW AFG 1984 0 1 0 0 0
ABW AFG 1985 0 1 0 0 0
答案 0 :(得分:0)
我假设da.f
(data.frame
的缩写,与已知函数无冲突)大致跟随您的结构,因为您没有在问题中包含它。
library(zoo)
#da.f is randomly generated in this example
da.f = data.frame(mid_o = sample(seq(0,4), 50, replace = TRUE), mid_d = sample(seq(0,4), 50, replace = TRUE))
#our result consists of 20 lags backward and forward in time
res = lag(as.zoo(da.f), -20:20, na.pad = TRUE)
2018年5月10日it was pointed to me by @thistleknot (thanks!) that dplyr
masks stats
's own lag
generic。因此,请确保您没有附加dplyr
,或明确地运行stats::lag
,否则我的代码将无法运行。
我想我找到了罪魁祸首:github.com/tidyverse/dplyr/issues/1586 回答:这是拥有大量R包的自然结果。 只需明确并使用stats :: lag或dplyr :: lag
答案 1 :(得分:0)
你好,谢谢你的帮助!
我找到了问题的解决方案:我必须首先将data.frame转换为data.table。 Seconly我找到了一种在data.table中创建多个列的方法,它们结合了命令template <class T, class... Args> void testFunc(int i) {
T t = 0;
std::cout << t << std::endl;
if constexpr (sizeof...(Args) > 0) {
testFunc<Args...>(i);
} else {
testFunc(i);
}
}
和sprintif
。我可以在4行代码中创建20个滞后和20个引线。
shift