简体   繁体   中英

Converting time variable from character with quarterly frequency

I have a data frame with quarterly frequency and 3 time variables, with time being a character variable. The data frame looks as follows

   dt <- structure(list(
  name1          =  c("C","C","C","C","C","C","B","B","B","B","B","B"),
  name2          =  c("D","E","A","D","E","A","D","E","A","D","E","A"),  
  year           =  c(2012, 2012, 2012, 2010, 2010, 2010, 2012, 2012, 2012, 2010, 2010, 2010 ),
  quarter        =  c(4,4,4,1,1,1,4,4,4,1,1,1),
  time           =  c("2012q4", "2012q4","2012q4","2010q1", "2010q1","2010q1","2012q4", "2012q4","2012q4","2010q1", "2010q1","2010q1")),
  .Names         =  c("name1","name2","year", "quarter", "time"),
  row.names      =  c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"), class =("data.frame")) 

I would like to set time as my time series variable and sort the data frame by name1 (alphabetically), name2 (alphabetically), and time(chronologically). The desired output should be

   dt <- structure(list(
 name1          =  c("B","B","B","B","B","B", "C","C","C","C","C","C"),
 name2          =  c("A", "A", "D", "D", "E", "E","A", "A", "D", "D", "E", "E"),  
 year           =  c(2010,2012,2010,2012,2010,2012,2010,2012,2010,2012,2010,2012),
 quarter        =  c(1,4,1,4,1,4,1,4,1,4,1,4),
 time           =  c("2010q1","2012q4", "2010q1","2012q4","2010q1","2012q4","2010q1","2012q4","2010q1","2012q4","2010q1","2012q4")),
 .Names         =  c("name1","name2","year", "quarter", "time"),
 row.names      =  c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"), class =("data.frame"))

I tried this.

 dt$time <- as.yearqtr(dt$time)
 dt <- dt[order(dt$name1, dt$name2, dt$time),]

Thanks in advance.

Why using $time rather than $year and $quarter ?

Just do dplyr::arrange(dt, name1, name2, year, quarter) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM