Created
March 22, 2011 18:53
-
-
Save noahhl/881799 to your computer and use it in GitHub Desktop.
The problem that makes write.table() not symmetric
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Create a data frame that includes a POSIXlt or POSIXct, write.table() to a file, and then read.table() of that file | |
> a <- data.frame(col1 = 1:10, col2 = as.POSIXlt(Sys.time()), stringsAsFactors=F) | |
> write.table(a, "test") | |
> read.table("test") | |
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : | |
line 1 did not have 4 elements | |
#Now, do the same with that data as a character instead: | |
> a <- data.frame(col1 = 1:10, col2 = as.character(Sys.time()), stringsAsFactors=F) | |
> write.table(a, "test2") | |
> read.table("test2") | |
col1 col2 | |
1 1 2011-03-22 14:37:11 | |
2 2 2011-03-22 14:37:11 | |
3 3 2011-03-22 14:37:11 | |
4 4 2011-03-22 14:37:11 | |
5 5 2011-03-22 14:37:11 | |
6 6 2011-03-22 14:37:11 | |
7 7 2011-03-22 14:37:11 | |
8 8 2011-03-22 14:37:11 | |
9 9 2011-03-22 14:37:11 | |
10 10 2011-03-22 14:37:11 | |
#Patch write.table() to quote POSIXlt and POSIXct when quoting, and this gets fixed | |
if (qset) | |
quote <- if (length(x)) | |
which(unlist(lapply(x, function(x) is.character(x) || | |
- is.factor(x)))) | |
+ is.factor(x) || is(x, "POSIXlt") || is(x, "POSIXct") ))) | |
else numeric(0L) | |
> a <- data.frame(col1 = 1:10, col2 = as.POSIXlt(Sys.time()), stringsAsFactors=F) | |
> write.table(a, "test3") | |
> read.table("test3") | |
col1 col2 | |
1 1 2011-03-22 14:53:09 | |
2 2 2011-03-22 14:53:09 | |
3 3 2011-03-22 14:53:09 | |
4 4 2011-03-22 14:53:09 | |
5 5 2011-03-22 14:53:09 | |
6 6 2011-03-22 14:53:09 | |
7 7 2011-03-22 14:53:09 | |
8 8 2011-03-22 14:53:09 | |
9 9 2011-03-22 14:53:09 | |
10 10 2011-03-22 14:53:09 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment