簡體   English   中英

如何用NA而不是X制作交叉表?

[英]How to make a cross table with NA instead of X?

我有以下數據集(參見下面的加載數據集)

     ID       Date qty
1  ID25 2007-12-01  45
2  ID25 2008-01-01  26
3  ID25 2008-02-01  46
4  ID25 2008-03-01   0
5  ID25 2008-04-01  78
6  ID25 2008-05-01  65
7  ID25 2008-06-01  32
8  ID99 2008-02-01  99
9  ID99 2008-03-01   0
10 ID99 2008-04-01  99

我想創建一個數據透視表。 我使用以下命令執行此操作,似乎工作正常:

pivottable <- xtabs(qty ~ ID + Date, table)

輸出如下:

ID     2007-12-01 2008-01-01 2008-02-01 2008-03-01 2008-04-01 2008-05-01 2008-06-01
ID25         45         26         46          0         78         65         32
ID99          0          0         99          0         99          0          0

但是,對於ID99,只有3個周期的值,其余的標記為“0”。 我想在第一個表中沒有值的字段中顯示NA。 我想得到一個如下表:

ID     2007-12-01 2008-01-01 2008-02-01 2008-03-01 2008-04-01 2008-05-01 2008-06-01
ID25         45         26         46          0         78         65         32
ID99         NA         NA         99          0         99         NA         NA

有關如何實現這一目標的任何建議?

加載數據集:

table <- structure(list(ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L), .Label = c("ID25", "ID99"), class = "factor"), Date = structure(c(7L, 
1L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L), .Label = c("01/01/2008", 
"01/02/2008", "01/03/2008", "01/04/2008", "01/05/2008", "01/06/2008", 
"01/12/2007"), class = "factor"), qty = c(45L, 26L, 46L, 0L, 
78L, 65L, 32L, 99L, 0L, 99L)), .Names = c("ID", "Date", "qty"
), class = "data.frame", row.names = c(NA, -10L))

table$Date <- as.POSIXct(table$Date, format='%d/%m/%Y')

您可以使用兩次xtabs來獲取您要查找的輸出:

  1. 創建表:

     pivottable <- xtabs(qty ~ ID + Date, table) 
  2. NA替換所有不存在的組合的零:

     pivottable[!xtabs( ~ ID + Date, table)] <- NA 

輸出:

      Date
ID     2007-12-01 2008-01-01 2008-02-01 2008-03-01 2008-04-01 2008-05-01 2008-06-01
  ID25         45         26         46          0         78         65         32
  ID99                               99          0         99                      

請注意,不顯示NA 這是由於這個類的print功能。 但是你可以使用unclass(pivottable)來實現print常規行為。

暫無
暫無

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

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