首页 > 解决方案 > 将 Inf(数字)写入 excel 并将其读回 R。 Inf 是 char,而不是数字

问题描述

Inf(as numeric) 写入后excel,我再次读回并得到InfChar。因为NaN,它变成了NA。因为NA, 它仍然NAnumeric, 这应该是。

我同时使用了readxlwritexl。我尝试安装tibble但失败了。

library(readxl)
library(writexl)

x <- c(1,NA)
y <- c(2,NaN)
z <- c(3,Inf)

d0 <- data.frame(x,y,z)

write_xlsx(d0, 'Test.xlsx')
d1 <- read_xlsx('Test.xlsx')

str(d0$x)
str(d0$y)
str(d0$z)

str(d1$x)
str(d1$y)
str(d1$z)

结果如下: 通知NaN变为NA; Inf( numeric) 变为Inf( character)

> str(d0$x)
 num [1:2] 1 NA
> str(d0$y)
 num [1:2] 2 NaN
> str(d0$z)
 num [1:2] 3 Inf

> str(d1$x)
 num [1:2] 1 NA
> str(d1$y)
 num [1:2] 2 NA
> str(d1$z)
 chr [1:2] "3" "Inf"

我正在寻找写入和读取阶段的解释和补救措施。阅读诸如设置之类的内容后,我不是在寻找解决方案as.numeric(d1$z)R我正在使用相同的代码验证第三方输出的数据集。

谢谢你的帮助!

标签: rtypesreadxldata-handlingwritexl

解决方案


有关更多信息,请参阅这个关于 excel 中无穷大的 SO 问题。Infinity 在 Excel 中不可用。在写入 excel 之前,您可以将Inf值设置为.Machine$double.xmax. 这将#NULL!在 excel 中表示。但是再次读入会#NULL!自动表示为InfR。奇怪的-Inf是,在 excel 中表示为相同的值#NULL!

library(readxl)
library(writexl)

d0 <- data.frame(x = c(1, NA),
                 y = c(2, NaN),
                 z = c(3, Inf),
                 z1 = c(4, -Inf))

d0[d0 == Inf] <- .Machine$double.xmax 
d0[d0 == -Inf] <- .Machine$double.xmax * -1


write_xlsx(d0, 'Test.xlsx')
d1 <- read_xlsx('Test.xlsx')
d1

# A tibble: 2 x 4
      x     y     z    z1
  <dbl> <dbl> <dbl> <dbl>
1     1     2     3     4
2    NA    NA   Inf  -Inf

如果您需要在 excel 中查看数字,则在将数据读回 R 后,您必须将这些Inf值替换为 Inf 并将其替换回 Inf。9.99999E+307


推荐阅读