在 R 中使用 write.fwf 进行 NA 处理

问题描述 投票:0回答:1

我正在尝试基于如下代码转换矩阵数据以进行数值模拟。 但是,我想保存 NA 值,以便没有空间,但我不知道。 有人可以告诉我吗?

library(gdata)

a <- matrix(c(1 : 6), nrow = 2, ncol = 3)
a[a == 6] <- NA

write.fwf(a, paste0("test.txt"), colnames = F, width = 17, justify = "right", na = "")

r dataframe na
1个回答
0
投票

在评论中,您澄清了您不想为

NA
值输出任何内容。在这种情况下,您不会编写固定宽度格式(因为您希望大多数值的宽度为 17,但 NA 的宽度为 0),因此您不应该使用
write.fwf()
。只需格式化值,将它们粘贴在一起,然后写入行即可。

例如:

a <- matrix(c(1 : 6), nrow = 2, ncol = 3)
a[a == 6] <- NA

formatted <- format(a, width = 17)
formatted[grepl("NA", formatted)] <- ""

lines <- apply(formatted, 1, paste0, collapse="")
writeLines(lines, "test.txt")
lines
#> [1] "                1                3                5"
#> [2] "                2                4"

创建于 2023-10-11,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.