I have a data.frame directly readed from an archive with this information:
ID date consumption
1 X1 19/02/2014 0
2 X1 19/05/2014 0
3 X1 20/08/2014 11
4 X1 18/11/2014 4
5 X2 19/02/2014 1
6 X2 19/06/2014 8
7 X2 20/08/2014 9
8 X3 18/11/2014 11
And i want to create a data.frame like this one:
X1 X2 X3
19/02/2014 0 1 NA
19/05/2014 0 NA NA
20/08/2014 11 9 NA
18/11/2014 4 NA 11
19/06/2014 NA 8 NA
with the dates as rownames and the ID as colnames. I've do it with the following code but i'm sure that must be another approach more efficient.
IDlist=mydataframe[!duplicated(mydataframe[,"ID"],),"ID"]
Datelist=mydataframe[!duplicated(mydataframe[,"date"],),"date"]
newdf=data.frame(matrix(NA, nrow = length(Datelist), ncol = length(IDlist)))
rownames(newdf)=Datelist
colnames(newdf)=IDlist
for(i in 1:nrow(mydataframe)){
mydataframe[newdf[i,"date"],newdf[i,"ID"]]=newdf[i,"consumption"]
}
Please, could anyone help me to do it more efficient? I'm pretty new programming in R.