根据R

时间:2017-02-25 23:19:35

标签: r list date object

我有一个数据框列表,我根据year.month格式的日期为它们分配了名称。但是,在列表本身中,数据框对象的存储顺序错误。

例如:

 [1] "2004.Apr" "2004.Aug" "2004.Dec" "2004.Feb" "2004.Jul" "2004.Jun" 
"2004.Mar" "2004.May" "2004.Nov" "2004.Oct" "2004.Jan"

所以我想将列表中的对象重新排序为下面所示的模式,即从1月到12月。有没有办法在不使用循环的情况下进行操作?

 [1] "2004.Jan" "2004.Feb" "2004.Mar" "2004.Apr" "2004.May" "2004.Jun" 
"2004.Jul" "2004.Aug" "2004.Sep" "2004.Oct" "2004.Nov" "2004.Dec"

3 个答案:

答案 0 :(得分:1)

您可以考虑列表名称和设置级别,但我假设您有许多不同的列表,包含年份和月份组合。您可以使用内置常量month.abb来获取相应的索引,如下所示:

# sample list
byMonthList <- list()[rep(1,11)]
names(byMonthList) <- c("2004.Apr", "2004.Aug", "2004.Dec", "2004.Feb", "2004.Jul", "2004.Jun", "2004.Mar", "2004.May", "2004.Nov", "2004.Oct", "2004.Jan")

# split month name from year.month names using strsplit 
# extract month name using sapply
ls_month <- sapply(strsplit(names(byMonthList), split="\\."), function(x) x[2])
ls_month
# [1] "Apr" "Aug" "Dec" "Feb" "Jul" "Jun" "Mar" "May" "Nov" "Oct" "Jan"

# use match and built in constant month.abb to get numeric value of months
ls_month_num <- match(ls_month, month.abb)
ls_month_num
# [1]  4  8 12  2  7  6  3  5 11 10  1

# Use ls_month_num to reorder your list
byMonthList[names(byMonthList)[order(ls_month_num)]]
# Or
byMonthList[names(byMonthList)[order(match(sapply(strsplit(names(byMonthList), split="\\."), function(x) x[2]), month.abb))]]

答案 1 :(得分:1)

zoo包具有as.yearmon函数,该函数返回一个&year;&#39; -classed值,该值实际上是数字,因此可以用作索引:

 inp[ order(zoo::as.yearmon(inp, format="%Y.%b"))]

 [1] "2004.Jan" "2004.Feb" "2004.Mar" "2004.Apr" "2004.May" "2004.Jun" "2004.Jul"
 [8] "2004.Aug" "2004.Oct" "2004.Nov" "2004.Dec"

数据输入:

inp <- scan(text='"2004.Apr" "2004.Aug" "2004.Dec" "2004.Feb" "2004.Jul" "2004.Jun" "2004.Mar" "2004.May" "2004.Nov" "2004.Oct" "2004.Jan"', what="")

答案 2 :(得分:0)

它们以这种方式重新排列,因为名称存储为字符向量。如果你执行as.factor(name_vector,levels = name_vector),那么它们将保持正确的顺序。