【问题标题】:Sudden changes on the original digits of data frame in R, when tapply() applied [duplicate]应用tapply()时,R中数据框的原始数字突然变化[重复]
【发布时间】:2017-10-12 12:36:25
【问题描述】:

我在R中经常使用tapply(),但我不知道为什么在应用tapply()函数后数量级会突然转换。

当我加载原始CSV数据时,数据显示如下。

Barcode        Group     Price
1002-01-23       A       10.23568975
1002-01-24       A       2356.25
1002-01-25       A       123.54897
1002-01-26       A       200.1548794

但是,我使用 R 代码后,Price 的数字转换如下。

Barcode        Group     Price         mean
1002-01-23       A       10.23569      672.5474
1002-01-24       A       2356.25000    672.5474
1002-01-25       A       123.54897     672.5474
1002-01-26       A       200.15488     672.5474

我希望得到 672.5473847875(=(10.23568975+2356.25+123.54897+200.1548794)/4) 作为平均值的结果。我该如何解决这个问题?让我给你看看我的 R 代码。

barcode <- read.csv("barcode.csv",header=T)
barcode$Group <- as.factor(barcode$Group)
barcode$Price <- as.numeric(barcode$Price)
test <- tapply(barcode$Price, barcode$Group, mean)
test1 <- data.frame(Group=names(test), mean=test)
barcode$mean <- test1$mean[match(barcode$Group, test1$Group)]

我真的需要你的帮助。非常感谢。

【问题讨论】:

  • 这几乎肯定与打印值有关,而不是与内部存储的值有关。例如,temp &lt;- 1.00045346643,然后在控制台中键入 temp。那就试试print(temp, digits=10)。
  • 请为特定于 RStudio 的问题保存 RStudio 标记 - 例如,如果您的代码在 RGui 中运行良好但在 RStudio 中不起作用。

标签: r tapply


【解决方案1】:

均值计算正确。看到这一点的最简单方法是对其进行测试:

barcode$mean == 672.5473847875
[1] TRUE TRUE TRUE TRUE

您可以更改默认打印的位数,例如

options(digits=15)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2014-02-17
    • 2019-04-28
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多