R 交叉表中按时间顺序排列的两位数年份

R 交叉表中按时间顺序排列的两位数年份,r,R,我有一个交叉表(由表)行中有个人,列中有年份。为了节省水平空间,我希望使用两位数的年份,而不是四位数的年份(下游通过xtable进入LaTeX)。但当我使用有序因子时(通过ordered()或因子(…,ordered=TRUE)),我得到的是数字排序,而不是时间排序 如何按时间顺序排列这些列?似乎当我将排序因子传递到表中时,我丢失了排序属性 # representative data dates <- as.Date("2010-01-01") - seq(30*365) DF <-

我有一个交叉表(由
)行中有个人,列中有年份。为了节省水平空间,我希望使用两位数的年份,而不是四位数的年份(下游通过
xtable
进入LaTeX)。但当我使用有序因子时(通过
ordered()
因子(…,ordered=TRUE)
),我得到的是数字排序,而不是时间排序

如何按时间顺序排列这些列?似乎当我将排序因子传递到
表中时,我丢失了排序属性

# representative data
dates <- as.Date("2010-01-01") - seq(30*365)
DF <- data.frame(day=sample(dates, 100, replace=TRUE),
                 id=sample(letters[1:5], 100, replace=TRUE))
DF$year <- as.numeric(format(DF$day, "%Y"))

# the table I want
table(DF$id, DF$year)

# but I'd like two year dates to save horizontal space
# but keep chronological order
DF <- DF[order(DF$day), ]
DF$yearShort <- factor(format(DF$day, "%y"), ordered=TRUE)

# but even though yearShort is ordered, the table isn't
is.ordered(DF$yearShort)
tab <- table(DF$id, DF$yearShort)
tab

# I can't order by rownames, either
tab[, order(dimnames(tab)[[2]])]
#代表性数据

日期我对这个解决方案不是很自豪,但它做到了您希望它做的事情:)

>tab2 colnames(tab2)tab2
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 98 99 00 01 02 03 04 05 06 07 08 09
02 02 02 02 01 02 01 01 01 01 01 01 01
b 1 1 0 2 0 0 0 1 2 1 0 0 2 0 1 1 1 0 0 1 3 0 1 0 0 0 1
C3101010101010010100101001001001001010101010101010101020
d 0 0 1 3 1 0 1 0 1 1 3 1 0 1 0 0 2 0 1 0 1 2 0 0 0 0 0 0 0
e10200310010003100020211010100

Sharp。这可能是唯一的解决办法。
> tab2 <- table(DF$id, DF$year)
> colnames(tab2) <- substr(colnames(tab2),3,4)
> tab2

    80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 98 99 00 01 02 03 04 05 06 07 08 09
  a  0  2  0  2  2  2  0  1  0  2  0  1  0  2  2  0  1  0  1  0  0  1  1  1  0  1  1  1  1
  b  1  1  0  2  0  0  0  0  1  2  1  0  0  0  2  0  1  1  1  0  0  1  3  0  1  0  0  0  1
  c  3  1  0  1  0  0  1  0  1  0  0  0  0  0  1  1  0  0  0  0  1  1  0  1  1  0  0  2  0
  d  0  0  1  3  1  0  1  0  0  1  1  3  1  1  0  1  0  0  2  0  1  0  1  2  0  0  0  0  0
  e  1  0  2  0  3  1  0  0  1  0  0  3  1  0  0  0  0  2  1  1  1  0  1  0  1  1  1  0  0