【问题标题】:Summarize an ordered factor总结一个有序因子
【发布时间】:2010-11-04 19:51:27
【问题描述】:

我在数据框中有一列包含有序因子。我通过融合数据然后对其进行转换来总结每个因素列中的条目数。到现在为止还挺好。但我需要包括不存在行的因素,以便汇总数据显示所有可能的因素,而不仅仅是使用的因素。

数据框:

> str(instats)
'data.frame':   75 obs. of  5 variables:
$ incident     : Factor w/ 75 levels "INC000000503771",..: 1 2 3 4 5 6 7 8 9 10 ...
$ submit.date  :Class 'Date'  num [1:75] 14907 14907 14907 14907 14907 ...
$ resolved.date:Class 'Date'  num [1:75] 14910 14907 14910 14907 14907 ...
$ closed.date  :Class 'Date'  num [1:75] 14913 14910 14913 14910 14910 ...
$ status       : Ord.factor w/ 6 levels "Opened"<"Resolved Pending Customer Action"<..: 5 5 5 5 5 5 5 5 5 5 ...
> 

到目前为止我做了什么:

> df.melt <- melt(instats,id=c('status'),measure=c('incident'))
> cast(df.melt, status ~ .,length)

我得到:

                            status (all)
1 Resolved Pending Customer Action    11
2               Pending xxx Action     3
3               Pending yyy Action     7
4                           Closed    54

我想要的是:

                            status (all)
1                           Opened     0
2 Resolved Pending Customer Action    11
3               Pending xxx Action     3
4               Pending yyy Action     7
5                           Closed    54
6                         Canceled     0

我明白为什么熔化/铸造会给我带来这样的结果。但是我还能如何做到这一点来获得我想要的结果呢?

【问题讨论】:

    标签: r


    【解决方案1】:

    你可以使用table

    instats <- data.frame(status=sample(letters[1:5],75,TRUE))
    instats$status <- factor(instats$status,levels=letters[1:6])
    
    table(instats$status)
    as.data.frame(table(instats$status))
    
    # or summary
    summary(instats$status)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多