导入read.csv/read.xlsx时将NA值插入数据框空白单元格 [英] Insert NA values into dataframe blank cells when importing read.csv/read.xlsx

查看:352
本文介绍了导入read.csv/read.xlsx时将NA值插入数据框空白单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随附的屏幕截图显示了我刚刚从excel文件导入到R中的数据框的一部分.在空白的单元格中,我需要插入"NA".如何将NA插入任何空白单元格中(而将已填充的单元格留空)?

The attached screenshot shows part of a dataframe which I have just imported into R from an excel file. In the cells which are blank, I need to insert 'NA'. How can I insert NA into any cell which is blank (whilst leaving the already populated cells alone)?

推荐答案

更好的问题是如何将其读入R,以便丢失的单元格已经是NA s.

The better question is how can I read it into R so the missing cells will already be NAs.

也许您使用过这样的东西:

Maybe you used something like this:

read.csv(file, header=FALSE,  strip.white = TRUE, sep=",")

在以下列方式阅读时,指定NA字符串:

Specify the NA strings like this when you read it in:

read.csv(file, header=FALSE,  strip.white = TRUE, sep=",",
    na.strings= c("999", "NA", " ", ""))  

实际回答您的问题.这种方法可能有效:

to actually answer your question. This approach could work:

#making fake data on a Saturday morning
dat <- data.frame(matrix(sample(c("", LETTERS[1:4]), 200, 
    replace=T, c(.6, rep(.1, 4))), 20))

#function to replace blanks with missing
blank2na <- function(x){ 
    z <- gsub("\\s+", "", x)  #make sure it's "" and not " " etc
    x[z==""] <- NA 
    return(x)
}

#apply that function
data.frame(sapply(dat,  blank2na))

这篇关于导入read.csv/read.xlsx时将NA值插入数据框空白单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆