r - 将 Inf(数字)写入 excel 并将其读回 R。 Inf 是 char,而不是数字
问题描述
将Inf
(as numeric
) 写入后excel
,我再次读回并得到Inf
Char。因为NaN
,它变成了NA
。因为NA
, 它仍然NA
是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
我正在使用相同的代码验证第三方输出的数据集。
谢谢你的帮助!
解决方案
有关更多信息,请参阅这个关于 excel 中无穷大的 SO 问题。Infinity 在 Excel 中不可用。在写入 excel 之前,您可以将Inf
值设置为.Machine$double.xmax
. 这将#NULL!
在 excel 中表示。但是再次读入会#NULL!
自动表示为Inf
R。奇怪的-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
推荐阅读
- if-statement - 是否可以使用行号作为谷歌表格中的逻辑表达式来执行 IF/THEN 语句?
- google-bigquery - 数据流作业失败并尝试在 Bigquery 上创建 temp_dataset
- python - 使用 SCRAPY 抓取特殊字符
- react-native - 从一个导航器中的屏幕导航到另一个导航器中的屏幕
- html - 带有垂直标题的引导卡
- python - 数据框列值列表
- javascript - 如何将 Reactjs 日志和指标推送到 Grafana
- sql - 验证备份内容而不重新创建它
- python - 导入以小数开头的文件夹
- python - 如何避免 tkinter 在导入过程中弹出窗口?