Home > OS >  Setting the first column as an index
Setting the first column as an index

Time:08-03

Is it possible to set the first column in my df to be the index? So my df becomes data of the 4 quarters by year, effectively year just becoming the index for plotting purposes

df snipet

df   
   year     Qtr1     Qtr2     Qtr3     Qtr4
 2 2005 13.950342 18.66797 21.73983 22.49755
 3 2006 17.116492 17.71430 20.50190 20.84159
 4 2007 18.918347 15.46002 17.87220 20.01701
 5 2008 18.508666 15.53064 16.06696 20.21658
 6 2009 16.255357 14.85671 15.28269 12.16084
 7 2010  8.889602 16.18042 19.74318 15.05649
 8 2011 15.130970 15.96652 17.79070 18.35192

Output required

 df   
 year     Qtr1     Qtr2     Qtr3     Qtr4
 2005 13.950342 18.66797 21.73983 22.49755
 2006 17.116492 17.71430 20.50190 20.84159
 2007 18.918347 15.46002 17.87220 20.01701
 2008 18.508666 15.53064 16.06696 20.21658
 2009 16.255357 14.85671 15.28269 12.16084
 2010  8.889602 16.18042 19.74318 15.05649
 2011 15.130970 15.96652 17.79070 18.35192

CodePudding user response:

dat <- structure(list(year = 2005:2011, Qtr1 = c(13.950342, 17.116492, 
18.918347, 18.508666, 16.255357, 8.889602, 15.13097), Qtr2 = c(18.66797, 
17.7143, 15.46002, 15.53064, 14.85671, 16.18042, 15.96652), Qtr3 = c(21.73983, 
20.5019, 17.8722, 16.06696, 15.28269, 19.74318, 17.7907), Qtr4 = c(22.49755, 
20.84159, 20.01701, 20.21658, 12.16084, 15.05649, 18.35192)), row.names = c(NA, 
-7L), class = "data.frame")

A simple solution is:

`row.names<-`(dat[-1], dat[[1]])
#          Qtr1     Qtr2     Qtr3     Qtr4
#2005 13.950342 18.66797 21.73983 22.49755
#2006 17.116492 17.71430 20.50190 20.84159
#2007 18.918347 15.46002 17.87220 20.01701
#2008 18.508666 15.53064 16.06696 20.21658
#2009 16.255357 14.85671 15.28269 12.16084
#2010  8.889602 16.18042 19.74318 15.05649
#2011 15.130970 15.96652 17.79070 18.35192

But a more stylish approach should be creating a quarterly time series:

ts(c(t(dat[-1])), start = c(2005, 1), frequency = 4)
#          Qtr1      Qtr2      Qtr3      Qtr4
#2005 13.950342 18.667970 21.739830 22.497550
#2006 17.116492 17.714300 20.501900 20.841590
#2007 18.918347 15.460020 17.872200 20.017010
#2008 18.508666 15.530640 16.066960 20.216580
#2009 16.255357 14.856710 15.282690 12.160840
#2010  8.889602 16.180420 19.743180 15.056490
#2011 15.130970 15.966520 17.790700 18.351920

CodePudding user response:

we can use column_to_rownames from tibble package

library(tidyverse)

as_tibble(df) |> column_to_rownames(var = "year")
  • output
         Qtr1     Qtr2     Qtr3     Qtr4
2005 13.950342 18.66797 21.73983 22.49755
2006 17.116492 17.71430 20.50190 20.84159
2007 18.918347 15.46002 17.87220 20.01701
2008 18.508666 15.53064 16.06696 20.21658
2009 16.255357 14.85671 15.28269 12.16084
2010  8.889602 16.18042 19.74318 15.05649
2011 15.130970 15.96652 17.79070 18.35192
  •  Tags:  
  • r
  • Related