Reputation: 259
I am attempting to use R's "reshape" package to alter a data frame I have, pasted below. Basically, I would like to create a new data frame which concatenates variables V2 and V3 into columns for all possible combinations of V2 and V3, with rows as date. I have attempted using reshape's cast function, however I am unable to get the Date to appear in the rows. The variables are concatenated in column names as I want, but the Date is not included.
This is the data frame std:
V2 V3 V5 Date
AUS CR 15344 2000-01-01
ALI NG 3952 2000-01-01
EUR CR 19296 2000-01-01
AUS MO 5826 2000-01-01
When I apply cast(std,Date~V2~V3,value="V5"), I obtain a frame as shown below, however I am unable to get the Date column to show as well. I have done lots of trial and error with cast and melt to no avail. Any suggestions would be appreciated
AUS.CR ALI.NG EUR.CR
15344 3952 19296
20108 4000 18568
Upvotes: 0
Views: 252
Reputation: 56905
You could use the package reshape
(function cast
) or reshape2
with dcast
:
x <- read.table(header=T,text='V2 V3 V5 Date
AUS CR 15344 2000-01-01
ALI NG 3952 2000-01-01
EUR CR 19296 2000-01-01
AUS MO 5826 2000-01-01')
With reshape
and cast
:
library(reshape)
cast(x, Date ~ V2 + V3, value='V5')
# Date ALI_NG AUS_CR AUS_MO EUR_CR
# 1 2000-01-01 3952 15344 5826 19296
With reshape2
and dcast
(same result)
library(reshape2)
dcast(x, Date ~ V2 + V3, value.var='V5')
Upvotes: 3