[R] Rearranging data

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Thu Feb 18 13:14:26 CET 2010


On Thu, Feb 18, 2010 at 9:21 AM, Anna Carter <anna_carter09 at yahoo.com> wrote:

> My objective is to rearrange filtered1 as
>
> date         corp1   corp2   corp11    corp17
> 17-Feb       65        95         30          16
> 16-Feb       70       135
> 15-Feb       69       140
> 14-Feb       89
> 13-Feb       88
>
> #(The above figures represent the corp-wise and date-wise rates for investment_id = 1.)
>
> Please guide me how the filtered1 can be rearranged?

 Ooh, so close! If you'd said 'reshaped' you'd be half way there:

> filtered1
   corp_id   date investment_id stock_rate
1    corp1 17-Feb             1         65
2    corp1 16-Feb             1         70
3    corp1 15-Feb             1         69
4    corp1 14-Feb             1         89
5    corp1 13-Feb             1         88
6    corp2 17-Feb             1         95
7    corp2 16-Feb             1        135
8    corp2 15-Feb             1        140
13  corp11 17-Feb             1         30
14  corp17 17-Feb             1         16

> cast(filtered1, date~corp_id,value="stock_rate")
    date corp1 corp11 corp17 corp2
1 13-Feb    88     NA     NA    NA
2 14-Feb    89     NA     NA    NA
3 15-Feb    69     NA     NA   140
4 16-Feb    70     NA     NA   135
5 17-Feb    65     30     16    95

The ordering is different to your desire but it's trivial to rearrange
it if you need. Also you get NA's where there's no value in that cell.

Are you doing this purely for presentation? Because if not then might
be easier to keep the data in the long format and work on it like that
with the various 'apply' type functions. See also the 'plyr' package.

Barry

-- 
blog: http://geospaced.blogspot.com/
web: http://www.maths.lancs.ac.uk/~rowlings
web: http://www.rowlingson.com/
twitter: http://twitter.com/geospacedman
pics: http://www.flickr.com/photos/spacedman



More information about the R-help mailing list