[datatable-help] Pivot part of a data table
Stefano Grioni
sgrioni at chicagobooth.edu
Mon Nov 9 02:32:23 CET 2015
Thanks Arun, it worked!
Here is my code, in case someone has the same question:
names = c("John", "Steve", "Peter")
ages = c(24,16,12)
grade_spring_quarter = c("A","B+", "C")
grade_summer_quarter = c("A+","B", "B+")
gift_spring_quarter = c("A gift","B+ gift", "C gift")
gift_summer_quarter = c("A+ gift","B gift", "B+ gift")
db <-
data.table(names,ages,grade_spring_quarter,grade_summer_quarter,gift_spring_quarter,gift_summer_quarter)
db.M <- melt(db, measure = patterns("^grade","^gift"), variable.name="quarter",
value.name=c("grades","gifts"))
Cheers,
Stefano
On Sun, Nov 8, 2015 at 1:44 PM Arunkumar Srinivasan <aragorn168b at gmail.com>
wrote:
> Hi, have a look at `?melt` and the reshaping vignette:
> https://github.com/Rdatatable/data.table/wiki/Getting-started
>
>
> --
> Arun
>
> On 8 November 2015 at 20:42:05, Stefano Grioni (sgrioni at chicagobooth.edu)
> wrote:
>
> Hello,
>
> I am new to R and trying to understand how data manipulation works. I have
> a CSV file which allows me to build a data table that looks like the
> following (simplified example):
>
> >db
> names ages grade_spring_quarter grade_summer_quarter
> 1: John 24 A A+
> 2: Steve 16 B+ B
> 3: Peter 12 C B+
>
> Now, my goal is to denormalize the data table in order to transform the
> last 2 columns in rows, therefore obtaining the following:
>
> > db2
> names ages quarter grades
> 1: John 24 spring A
> 2: Steve 16 spring B+
> 3: Peter 12 spring C
> 4: John 24 summer A+
> 5: Steve 16 summer B
> 6: Peter 12 summer B+
>
> I think that I would be able to do it using for loops, but I doubt that's
> the most efficient way. I have started looking into the Join functionality
> of data table but so far didn't manage to build db2 from db that way.
>
> Do you see how I could proceed?
>
> Many thanks
>
> Stefano
>
> _______________________________________________
> datatable-help mailing list
> datatable-help at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20151109/b117b685/attachment.html>
More information about the datatable-help
mailing list