Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a zoo object without the index

Tags:

r

zoo

I have a zoo object (tmp) which has date and time as index and a value like below

> library(zoo)
> library(chron)
> tmp
(01/01/97 00:00:00) (01/01/97 01:00:00) (01/01/97 02:00:00) 
            5.0                 3.2                 6.7 
> dput(tmp)
structure(c(5, 3.2, 6.7), index = structure(c(9862, 9862.04166666667, 
9862.08333333333), format = structure(c("m/d/y", "h:m:s"), .Names = c("dates", 
"times")), origin = structure(c(1, 1, 1970), .Names = c("month", 
"day", "year")), class = c("chron", "dates", "times")), class = "zoo")

I am trying to write this zoo object to a text file and I just want the values written in the text file. I used the following code:

write.zoo(tmp,file="D:/test.txt", row.names=FALSE, quote=FALSE, na="")

and I get the following file:

(01/01/97 00:00:00) 5
(01/01/97 01:00:00) 3.2
(01/01/97 02:00:00) 6.7

but the output I want is

5
3.2
6.7

Can anyone tell me how to get this?

like image 212
user1807652 Avatar asked Nov 19 '25 22:11

user1807652


1 Answers

Convert the data to a normal vector first, and write that as a normal table:

write.table(as.vector(tmp), file="D:/test.txt",
            row.names=FALSE, col.names=FALSE, quote=FALSE, na="")

Actually the conversion to a vector appears to be unneccessary, but I consider it clearer as you indicate that you are throwing away the extra data zoo associates with these values.

As Joshua Ulrich write in a comment below, in case your tmp object has more than one column, you should probably use coredata instead of as.vector:

write.table(coredata(tmp), file="D:/test.txt",
            row.names=FALSE, col.names=FALSE, quote=FALSE, na="")

The difference is that this will generate a file with multiple columns, whereas as.vector will generate a single column by simply writing out column vectors one after the other. Depends on your use case.

I guess (though I might be wrong) that the following works like the coredata version:

write.table(tmp, file="D:/test.txt",
            row.names=FALSE, col.names=FALSE, quote=FALSE, na="")
like image 123
MvG Avatar answered Nov 22 '25 12:11

MvG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!