在将Inf (作为numeric)写入excel之后,我再次读取它,并将Inf作为Char。对于NaN,它变成了NA。对于NA,它仍然是NA as numeric,这是理所当然的。
我同时使用了readxl和writexl。我尝试安装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代码验证第三方输出的数据集。
谢谢你的帮忙!
发布于 2019-07-21 17:57:36
有关更多信息,请参阅this关于excel中的无穷大的问题。无穷大在excel中不可用。在写入excel之前,可以将Inf值设置为.Machine$double.xmax。这将在excel中表示为#NULL!。但再次读取#NULL!将自动表示为R中的Inf。奇怪的是,-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中的数字,则必须将Inf值替换为9.99999E+307,并在将数据读回R后将此数字替换回Inf。
https://stackoverflow.com/questions/57129856
复制相似问题