【问题标题】:Replace missing value with character from 'pivottabler' package用“pivottabler”包中的字符替换缺失值
【发布时间】:2021-01-23 18:10:14
【问题描述】:

我正在使用“pivottabler”包来制作交叉表。但是表中存在一些缺失值。

我想知道是否可以选择将缺失值替换为“-”之类的内容。

【问题讨论】:

    标签: r pivot-table


    【解决方案1】:

    总结

    有两种不同的选择 - 取决于您的场景:

    1. 如果数据组组合在数据框中没有匹配的行,请使用 noDataCaption 参数。
    2. 如果数据框中的数据组组合确实存在行,但值为 NA,请使用 exportOptions 参数。

    选项 1 - noDataCaption

    使用defineCalculation() 函数的noDataCaption 参数。

    更多信息: http://pivottabler.org.uk/articles/v03-calculations.html#empty-cells-1

    在下面的示例中,bhmtrains 数据框中没有“Virgin Trains”的“Ordinary Passenger”火车。在示例 2 中,将空单元格更改为显示破折号。

    library(pivottabler)
    
    # example 1 - normal output
    library(pivottabler)
    pt <- PivotTable$new()
    pt$addData(bhmtrains)
    pt$addColumnDataGroups("TrainCategory")
    pt$addRowDataGroups("TOC")
    pt$defineCalculation(calculationName="TotalTrains", summariseExpression="n()")
    pt$renderPivot()
    
    # example 2 - display dash where no data exists
    library(pivottabler)
    pt <- PivotTable$new()
    pt$addData(bhmtrains)
    pt$addColumnDataGroups("TrainCategory")
    pt$addRowDataGroups("TOC")
    pt$defineCalculation(calculationName="TotalTrains", 
                         summariseExpression="n()", noDataCaption="-")
    pt$renderPivot()
    

    选项 2 - exportOptions

    使用pt$renderPivot() 函数的exportOptions 参数。

    在下面的代码中,示例 1 是正常输出,示例 2 将 NA 更改为破折号。

    更多信息: http://pivottabler.org.uk/articles/vA1-appendix.html#output-of-na-nan-inf-and-inf

    在下面的示例中,数据框中有一行颜色为“绿色”,但它的值为 NA。在示例 2 中,为颜色“Green”输出一个破折号而不是 NA。

    library(pivottabler)
    
    someData <- data.frame(Colour=c("Red", "Yellow", "Green", "Blue", "White", "Black"),
                           SomeNumber=c(1, 2, NA, NaN, -Inf, Inf))
    
    # example 1 - normal output
    pt <- PivotTable$new()
    pt$addData(someData)
    pt$addRowDataGroups("Colour")
    pt$defineCalculation(calculationName="Total", summariseExpression="sum(SomeNumber)")
    pt$evaluatePivot()
    pt$renderPivot()
    
    # example 2 - change NA to dash
    pt <- PivotTable$new()
    pt$addData(someData)
    pt$addRowDataGroups("Colour")
    pt$defineCalculation(calculationName="Total", summariseExpression="sum(SomeNumber)")
    pt$evaluatePivot()
    pt$renderPivot(exportOptions=list(exportNAAs="-"))
    

    【讨论】:

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