[R] Converting data.frame from long to wide format
Phil Spector
spector at stat.berkeley.edu
Thu Dec 9 03:53:10 CET 2010
Another way, using just base R is
> reshape(df,idvar='y',timevar='x',v.names='z',direction='wide')
y z.A z.B z.C
1 D a b c
4 E d e f
7 F g h i
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Wed, 8 Dec 2010, Matthew Pettis wrote:
> Hi Jonathan,
>
> Thank you very much! I was about to recall this after I found this
> discussion (https://stat.ethz.ch/pipermail/r-help/2008-June/164440.html),
> but I think your solution is more tidy.
>
> Thank you very much!
> Matt
>
> On Wed, Dec 8, 2010 at 8:33 PM, Jonathan Christensen <dzhonatan at gmail.com>wrote:
>
>> Matt,
>>
>> library(reshape2)
>> wide.df <- dcast(df, y ~ x)
>>
>> Works great for me.
>>
>> Jonathan
>>
>>
>> On Wed, Dec 8, 2010 at 7:26 PM, Matthew Pettis <matthew.pettis at gmail.com>
>> wrote:
>>> Hi,
>>>
>>> I was wondering if there is an easy way that I am missing for turning a
>> long
>>> dataframe into a wide one. Below is sample code that will make what I
>> have
>>> and, in comments, the form of what I want:
>>>
>>> # Have: dataframe like 'df'
>>> df <- expand.grid( x=LETTERS[1:3], y=LETTERS[4:6])
>>> df$z <- letters[1:length(df[,1])]
>>>
>>> # Want: data.frame that has following form:
>>> # A B C
>>> # D a b c
>>> # E d e f
>>> # F g h i
>>>
>>>
>>> I looked at 'xtabs' and 'cast' from reshape/reshape2, but unless I'm
>>> misunderstanding something, these will work only for the 'z' column being
>>> numeric, not textual. Is there an easy way to do this with 'z' being
>>> textual rather than numeric?
>>>
>>> tia,
>>> Matt
>>>
>>> [[alternative HTML version deleted]]
>>>
>>> ______________________________________________
>>> R-help at r-project.org mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-help
>>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>>> and provide commented, minimal, self-contained, reproducible code.
>>>
>>
>
>
>
> --
> Seven Deadly Sins (Gandhi):
> - Wealth without work - Politics without principle
> - Pleasure without conscience - Commerce without morality
> - Science without humanity - Worship without sacrifice
> - Knowledge without character
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list