Reputation: 1493
I cannot find a similar problem on StackOverflow. I apologize if it is out there...
I have a list of dataframes, all with a date column and a value for each date. I would like to combine this list into one dataframe, with one data column, and the value from each list.
I have this:
> list
$IBM
Date IBM
1 2012-03-01 98
2 2012-03-02 94
3 2012-03-03 49
4 2012-03-04 48
$AAPL
Date AAPL
1 2012-03-01 43
2 2012-03-02 38
3 2012-03-03 13
4 2012-03-04 10
$HPQ
Date HPQ
1 2012-03-01 62
2 2012-03-02 67
3 2012-03-03 24
4 2012-03-04 37
I would like this:
Date IBM AAPL HPQ
1 2012-03-01 98 43 62
2 2012-03-02 94 38 67
3 2012-03-03 49 13 24
4 2012-03-04 48 10 37
Using do.call("cbind", list)
I get this:
> do.call("cbind", test)
IBM.Date IBM.IBM AAPL.Date AAPL.AAPL HPQ.Date HPQ.HPQ
1 2012-03-01 98 2012-03-01 43 2012-03-01 62
2 2012-03-02 94 2012-03-02 38 2012-03-02 67
3 2012-03-03 49 2012-03-03 13 2012-03-03 24
4 2012-03-04 48 2012-03-04 10 2012-03-04 37`
This is very simliar to what I want, but with multiple repeated date columns. Is there a way to do this? Preferably in the base package?
Thanks!!!
Upvotes: 0
Views: 199
Reputation: 206232
If your list looks like this
#sample data
dts<-c("2012-03-01","2012-03-02","2012-03-03","2012-03-04")
dd<-list(
IBM=data.frame(Date=dts, IBM=c(98,94,49,48)),
APPL=data.frame(Date=dts, APPL=c(43,38,13,10)),
HPQ=data.frame(Date=dts, HPQ=c(62,67,24,37))
)
Then you can create the output you want with
Reduce(merge, dd)
# Date IBM APPL HPQ
# 1 2012-03-01 98 43 62
# 2 2012-03-02 94 38 67
# 3 2012-03-03 49 13 24
# 4 2012-03-04 48 10 37
Upvotes: 1