我有一个具有季度频率和3个时间变量的数据框, time 是一个字符变量。数据框如下所示
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"))
我想将 time 设置为我的时间序列变量,并按名称1(按字母顺序),名称2(按字母顺序)和时间(按时间顺序)对数据框进行排序。所需的输出应为
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"))
我试过了。
dt$time <- as.yearqtr(dt$time)
dt <- dt[order(dt$name1, dt$name2, dt$time),]
提前致谢。
答案 0 :(得分:0)
为什么使用$time
而不是$year
和$quarter
?
只需dplyr::arrange(dt, name1, name2, year, quarter)
。