Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write.table converting NaNs to NA

Tags:

r

I have a data frame

a = data.frame("a"=c(1,2,3,NA,NaN,6),"b"=c(NA,NA,NaN,1,2,3),"c"=c(1,2,NA,NA,5,6))

I am writing it to a file

write.table(a,file="t.txt",row.names=FALSE,quote=FALSE,sep="\t")

Its converting "NaN" to "NA". I want to retain the original values. How can I do that? I want to keep NaN and NA in my t.txt. But I get all NA in my t.txt

like image 807
user1631306 Avatar asked Feb 16 '23 03:02

user1631306


1 Answers

I'm not sure there's a way to do it directly, but you can always convert the columns to character, then write it (since you're using quote=FALSE).

> a[] <- lapply(a, as.character)
> write.table(a,file="t.txt",row.names=FALSE,quote=FALSE,sep="\t")
> str(read.table("t.txt",header=TRUE))
'data.frame':   6 obs. of  3 variables:
 $ a: num  1 2 3 NA NaN 6
 $ b: num  NA NA NaN 1 2 3
 $ c: int  1 2 NA NA 5 6
like image 157
Joshua Ulrich Avatar answered Feb 18 '23 12:02

Joshua Ulrich