所以我得到的数据如下所示:
id year principal interest
1: 011000600 2013 0.00 0.00
2: 011000600 2014 544.03 0.00
3: 011000700 2013 0.00 0.00
4: 011000700 2014 0.01 0.00
5: 011000800 2013 363.44 12.79
6: 011000800 2014 2005.98 0.00
7: 011000900 2013 0.00 0.00
8: 011000900 2014 0.00 0.00
9: 011001000 2013 0.00 0.00
10: 011001000 2014 0.00 0.00
11: 011001100 2013 0.00 0.00
12: 011001100 2014 1723.24 0.00
13: 011001560 2013 0.00 0.00
14: 011001560 2014 0.00 0.00
15: 011001650 2013 0.00 0.00
16: 011001650 2014 0.00 0.00
(基本上是一堆变量的纵向样本)
数据偏大,所以我正在使用data.table
对于一切。我重塑它以获得每个id
按行唯一:
datam<-melt(data,id=c("id","year"))
data1<-dcast.data.table(datam,id~...)
这产生:
id 2013_principal 2013_interest 2014_principal 2014_interest
1: 011000600 0.00 0.00 544.03 0
2: 011000700 0.00 0.00 0.01 0
3: 011000800 363.44 12.79 2005.98 0
4: 011000900 0.00 0.00 0.00 0
5: 011001000 0.00 0.00 0.00 0
6: 011001100 0.00 0.00 1723.24 0
这当然是form我想要的数据,但是列名以数字开头是一件痛苦的事。
对于如何处理这个问题有什么建议吗?我更愿意:
id principal_2013 interest_2013 principal_2014 interest_2014
1: 011000600 0.00 0.00 544.03 0
2: 011000700 0.00 0.00 0.01 0
3: 011000800 363.44 12.79 2005.98 0
4: 011000900 0.00 0.00 0.00 0
5: 011001000 0.00 0.00 0.00 0
6: 011001100 0.00 0.00 1723.24 0
(将年份切换为后缀)
我尝试在铸造时更加明确,例如
data2<-dcast.data.table(datam,id~year+...)
data3<-dcast.data.table(datam,id~...+year)
无济于事:
data2
id 2013_principal 2013_interest 2014_principal 2014_interest
1: 011000600 0.00 0.00 544.03 0
2: 011000700 0.00 0.00 0.01 0
3: 011000800 363.44 12.79 2005.98 0
4: 011000900 0.00 0.00 0.00 0
5: 011001000 0.00 0.00 0.00 0
6: 011001100 0.00 0.00 1723.24 0
data3
id 2013_principal 2013_interest 2014_principal 2014_interest
1: 011000600 0.00 0.00 544.03 0
2: 011000700 0.00 0.00 0.01 0
3: 011000800 363.44 12.79 2005.98 0
4: 011000900 0.00 0.00 0.00 0
5: 011001000 0.00 0.00 0.00 0
6: 011001100 0.00 0.00 1723.24 0
考虑到我认为这种类型的重塑是普遍存在的,因此 dcast 的命名约定默认为这种风格似乎很愚蠢。
我还尝试根据我发现的其他一些帖子(例如here https://stackoverflow.com/questions/10662314/r-rename-subset-of-variables-in-data-frame),但运行速度慢得难以想象(完整数据集中大约有 400 个变量需要重命名)
names(data)<-ifelse(substr(names(data),1,2) %in% c("19","20"),
paste(substr(names(data),6,nchar(data)),
substr(names(data),1,4),sep="_") ,
names(copy))
(我试图找到以年份开头的所有变量 - 19xx 或 20xx - 并尝试交换开头和结尾)