R:使用完整案例编写表格以排除NA

时间:2017-08-08 23:03:38

标签: r

我尝试使用R从较大的输入数据文件中仅选择和写入三列,并将每个列输出为自己的.txt文件。必须有相当多的空白单元格,R正确输出我的.txt文件,但空格输出为NA,如下所示:

NA
NA
NA
NA
NA
138.388
142.604
NA
NA
NA
172.566

与我需要的相反,即:

138.388
142.604
172.566

我目前的代码如下:

indata <- read.delim("mydata.txt",header=T,sep="\t",stringsAsFactors=F)
# columns to print
outcols <- c("Column1.info","Column2.info","Column3.info")

## loop through columns to print
for(outcol in outcols){
    # form outfile name
    outfilename <- paste0(gsub(".info","",outcol),".txt")
    # write column of interest
    write.table(indata[,outcol,drop=F],file=outfilename,sep="\t",quote=F,col.names=F,row.names=F)
}

我正在使用R,因为它比MATLAB更好地处理空白单元格;但是我如何使用例如complete.cases()(或其他东西)来只写相关数据呢?

1 个答案:

答案 0 :(得分:0)

na.omit() will remove the entire row.

如果您只想从col中删除NA元素。试试这可能会有所帮助。考虑df是你的三个cols的数据集。

list <- apply(df,2,function(x) x[!is.na(x)])# Removing NA row wise
Len <- max(sapply(list,length)).#Creating a standard matrix by replacing blanks with NA in the end 
data <-sapply(list,function(x) c(x,rep(NA,len-length(x))))