簡體   English   中英

交叉表中按時間順序排列的兩位數年份

[英]Chronologically order two-digit years in cross table

我有一個交叉表(用table制成),其中個人在行中,年份在列中。 為了節省水平空間,我想使用兩位數的年份,而不是四位數的年份(在下游通過xtable進入LaTeX)。 但是,當我使用有序因子(通過ordered()factor(..., ordered=TRUE) )時,我得到的是數字排序,而不是時間順序。

如何按時間順序排列列? 似乎當我將有序因子傳遞到table我失去了排序屬性。

# 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 <- 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM