Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201867

Reshape by id and keep other variables fixed

$
0
0

What I'm trying to do is reorder the data where the data is in columns, but the rest of the variables are maintained

       c1<- c("ID","Location", "Year","Gender", "MoneySpent", "MoneyWithCreditCard")
         c2<- c(1,"EEUU",2007,"M",1500,400)
         c3<- c(1,"EEUU",2008,"M",3900,0)
         c4<- c(1,"EEUU",2009,"M",0,100)
         c5<- c(2,"Germany",2007,"F",0,1000)
         c6<- c(2,"Germany",2008,"F",4000,500)
         c7<- c(2,"Germany",2009,"F",700,0)
         c8<- c(2,"Germany",2010,"F",0,50)
         Df<-data.frame(rbind(c2,c3,c4,c5,c6,c7,c8))
         colnames(Df)<-c1   

#   ID Location Year Gender MoneySpent   MoneyWithCreditCard   TypeofHome
#c2  1     EEUU 2007      M       1500        400                House
#c3  1     EEUU 2008      M       3900         0                 House
#c4  1     EEUU 2009      M          0        100                House
#c5  2  Germany 2007      F          0        1000               Department
#c6  2  Germany 2008      F       4000        500                Department
#c7  2  Germany 2009      F        700         0                 Department
#c8  2  Germany 2010      F          0         50                Department

The result I need is this one:

# ID Location Gender TypeofHome MS.2007 MS.2008 MS.2009 MS.2010 MWC.2007 MWC.2008 MWC.2009 MWC.2010
# 1   EEUU      M      House     1500    3900      0      NA      400       0        100     NA
# 2   Germany   F      Department 0      4000     700      0     1000      500       0       50

Which one is the better solution? Thanks btw!


Viewing all articles
Browse latest Browse all 201867

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>