[R] turning a list of objects into columns

Gerrit Draisma gdr@|@m@ @end|ng |rom x@4@||@n|
Sun Jun 30 16:34:11 CEST 2019


Ha Janet,
Does this reshape do what you want:
df = read.table(header=TRUE,text="
scen streamflow    trans     evap      psn
1   0.019234 1.658967 0.002883 0.002391
1   0.019027 1.661192 0.002844 0.003142
2   0.018821 1.695623 0.003192 0.002167
2   0.018619 1.503481 0.002536 0.003059
3   0.018425 0.000008 1.880355 0.002592
3   0.018369 0.100551 2.225793 0.006642
")
df$t <- 1:2
# reshape(df,idvar="scen",timevar="t",direction="wide")
reshape(df,idvar="t",timevar="scen",direction="wide")

HTH, Gerrit

 > Date: Sat, 29 Jun 2019 12:45:46 -0700
 > From: Jeff Newmiller <jdnewmil using dcn.davis.ca.us>
 >
 > Maybe look at reshape2? e.g. https://seananderson.ca/2013/10/19/reshape/
 >
 > There is a very capable base R reshape function, but I find it quite
 > challenging to apply.
 >
 > Note that you normally want to retain one or more columns to identify
 > each row in your result... but I am not sure I see anything suitable
 > in your example data. You may have removed it, or it may have been
 > implied and you may need to create something that will do the job.
 >
 > e.g. https://www.studytonight.com/dbms/database-key.php
 >
 > On June 29, 2019 11:27:40 AM PDT, Janet Choate <jsc.eco using gmail.com> wrote:
 > > Hi,
 > > I have a data frame that looks something like this (but much longer):
 > > df
 > > scen streamflow    trans     evap      psn
 > > 1   0.019234 1.658967 0.002883 0.002391
 > > 1   0.019027 1.661192 0.002844 0.003142
 > > 2   0.018821 1.695623 0.003192 0.002167
 > > 2   0.018619 1.503481 0.002536 0.003059
 > > 3   0.018425 0.000008 1.880355 0.002592
 > > 3   0.018369 0.100551 2.225793 0.006642
 > >
 > > i want to end up with something like this (for each variable -
 > > streamflow,
 > > trans, evap, psn). using the variable trans here as an example:
 > > trans1        trans2      trans3
 > > 1.658967  1.695623  0.000008
 > > 1.661192  1.503481  0.100551
 > >
 > > so that each variable (streamflow, trans, evap, psn) is in a separate
 > > column based on the scen #.
 >



More information about the R-help mailing list