我在数据表中有一个专栏,我想重复17年。我希望将这组相同的值放入一列并命名。
更确切地说,我的数据如下,它被称为“mean_exp_TOD”。
TheInterval mean_Exports
1: 0 0.000000e+00
2: 1 0.000000e+00
3: 2 0.000000e+00
4: 3 0.000000e+00
5: 4 0.000000e+00
6: 5 0.000000e+00
7: 6 0.000000e+00
8: 7 0.000000e+00
9: 8 3.278689e-05
10: 9 6.933060e-03
11: 10 1.747746e-01
12: 11 1.330710e+00
13: 12 4.628286e+00
14: 13 1.097312e+01
15: 14 2.067735e+01
16: 15 3.214487e+01
17: 16 4.381565e+01
18: 17 5.434046e+01
19: 18 6.208044e+01
20: 19 6.807106e+01
21: 20 7.212614e+01
22: 21 7.434484e+01
23: 22 7.452706e+01
24: 23 7.376302e+01
25: 24 7.110812e+01
26: 25 6.784952e+01
27: 26 6.270421e+01
28: 27 5.503787e+01
29: 28 4.597257e+01
30: 29 3.537733e+01
31: 30 2.398188e+01
32: 31 1.262636e+01
33: 32 4.892807e+00
34: 33 1.284960e+00
我想要的是创建一个新数据表,其中包含一个名为“TheInterval”的列,该列从我的代码段获取值。然后我只想根据Years创建一个列。
我一直在做的是:
Years <- c(1999:2016)
for (i in Years){
mean_EXP <- mean_exp_TOD[, list(Interval = c(0:47), i = mean_exp_TOD[,mean_Exports])]
}
然而,然后返回: (我仅仅因为解释原因而缩短了它)
Interval i
1: 0 0.000000e+00
2: 1 0.000000e+00
3: 2 0.000000e+00
4: 3 0.000000e+00
5: 4 0.000000e+00
6: 5 0.000000e+00
7: 6 0.000000e+00
8: 7 0.000000e+00
9: 8 3.278689e-05
也没有错误或警告。
所以我没有得到名为“1999”,“2000”,“2001”......的17列填充了mean_Exports数据,而是只得到一个名为i的列!
任何帮助?
答案 0 :(得分:3)
我们可以这样做(如果我们不需要使用for
循环)
mean_exp_TOD[, paste0(Years) := mean_Exports]
tail(mean_exp_TOD)
# TheInterval mean_Exports 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
#1: 28 45.972570 45.972570 45.972570 45.972570 45.972570 45.972570 45.972570 45.972570 45.972570 45.972570 45.972570 45.972570 45.972570 45.972570
#2: 29 35.377330 35.377330 35.377330 35.377330 35.377330 35.377330 35.377330 35.377330 35.377330 35.377330 35.377330 35.377330 35.377330 35.377330
#3: 30 23.981880 23.981880 23.981880 23.981880 23.981880 23.981880 23.981880 23.981880 23.981880 23.981880 23.981880 23.981880 23.981880 23.981880
#4: 31 12.626360 12.626360 12.626360 12.626360 12.626360 12.626360 12.626360 12.626360 12.626360 12.626360 12.626360 12.626360 12.626360 12.626360
#5: 32 4.892807 4.892807 4.892807 4.892807 4.892807 4.892807 4.892807 4.892807 4.892807 4.892807 4.892807 4.892807 4.892807 4.892807
#6: 33 1.284960 1.284960 1.284960 1.284960 1.284960 1.284960 1.284960 1.284960 1.284960 1.284960 1.284960 1.284960 1.284960 1.284960
# 2012 2013 2014 2015 2016
#1: 45.972570 45.972570 45.972570 45.972570 45.972570
#2: 35.377330 35.377330 35.377330 35.377330 35.377330
#3: 23.981880 23.981880 23.981880 23.981880 23.981880
#4: 12.626360 12.626360 12.626360 12.626360 12.626360
#5: 4.892807 4.892807 4.892807 4.892807 4.892807
#6: 1.284960 1.284960 1.284960 1.284960 1.284960
答案 1 :(得分:2)
mean_EXP <- data.table(Interval = 1:47)
for(i in Years) {
mean_EXP[,as.character(i) := mean_exp_TOD[,mean_Exports]]
}
编辑:我认为你这样做是为了做一个更复杂的选择,每年都依赖于前一年?否则,您可以使用以下内容一次创建所有内容:
mean_EXP[,as.character(Years) := replicate(length(Years),
mean_exp_TOD[,mean_Exports],
simplify = FALSE)]