简体   繁体   English

在R中使用格式时如何保留NA?

[英]How to preserve NAs when using format in R?

I have a matrix with some NA that I'd like to format and then write to a CSV file, replacing each NA with two dashes. 我有一个带有NA的矩阵,我想格式化然后写入CSV文件,用两个破折号替换每个NA However, all of the NA get converted to characters by format , and write.csv then fails to detect and replace them. 但是,所有NA都按format转换为字符,然后write.csv无法检测并替换它们。

After reading through the help file for format , setting na.encode=FALSE seemed like the logical thing to do, but that didn't fix the problem. 在阅读了format的帮助文件之后,设置na.encode=FALSE似乎是合乎逻辑的事情,但这并没有解决问题。 I've also searched with Google and on this site for other people having this problem, but couldn't find any. 我还搜索过谷歌和本网站上的其他人有这个问题,但找不到任何问题。 This seems like it should have a simple answer, and has me beating my head against the wall. 这似乎应该有一个简单的答案,并让我头撞墙。

A minimal example of my code looks like this: 我的代码的最小示例如下所示:

data = matrix(c(pi, NA, pi*100, NA), 2, 2)
data.f = format(data, digits=4, nsmall=2)
write.csv(data.f, file="data.csv", na="--")

I'm using R 2.15.1. 我正在使用R 2.15.1。 What is the correct way to do this? 这样做的正确方法是什么?

Edit: Can anyone explain why this even requires a workaround? 编辑:任何人都可以解释为什么这甚至需要一个解决方法?

There's probably a more orthodox way to do this, but perhaps you can use !is.na() at the format() stage to prevent the NA values from being converted to characters. 这可能是一种更正统的方法,但也许您可以在format()阶段使用!is.na()来防止NA值转换为字符。

Here's a minimal example along with the resulting CSV. 这是一个最小的例子以及生成的CSV。

set.seed(1)
data <- matrix(rnorm(20), ncol=5)
data[sample(length(data), 5)] <- NA
data.f <- data
data.f[!is.na(data.f)] <- format(data.f[!is.na(data.f)], digits = 4, nsmall = 2)
write.csv(data.f, file = "data.csv", na = "--")
dput(write.csv(data.f, na = "--"))
# "","V1","V2","V3","V4","V5"
# "1","-0.62645"," 0.32951",--,--,--
# "2"," 0.18364","-0.82047",--,"-2.21470"," 0.94384"
# "3","-0.83563"," 0.48743"," 1.51178",--," 0.82122"
# "4"," 1.59528"," 0.73832"," 0.38984","-0.04493"," 0.59390"
# NULL

Here is a possible workaround 这是一个可能的解决方法

data = matrix(c(pi, NA, pi*100, NA), 2, 2)
data.f = format(data, digits=4, nsmall=2)
data.f <- replace(data.f, which(data.f == "     NA"), "--")
write.csv(data.f, file="data.csv")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM