If you have a data.frame
with numeric columns the conversion is without problems, as explained here.
dtf=data.frame(matrix(rep(5,10),ncol=2))
#str(dtf)
dtfz <- zoo(dtf)
class(dtfz)
#[1] "zoo"
str(as.data.frame(dtfz))
#'data.frame': 5 obs. of 2 variables:
# $ X1: num 5 5 5 5 5
# $ X2: num 5 5 5 5 5
But if you have a data.frame
with text columns everything is converted to factors, even when setting stringsAsFactors = FALSE
dtf=data.frame(matrix(rep("d",10),ncol=2),stringsAsFactors = FALSE)
#str(dtf)
dtfz <- zoo(dtf)
#class(dtfz)
#dtfz
All the following convert the strings to factors:
str(as.data.frame(dtfz))
str(as.data.frame(dtfz,stringsAsFactors = FALSE))
str(data.frame(dtfz))
str(data.frame(dtfz,stringsAsFactors = FALSE))
str(as.data.frame(dtfz, check.names=FALSE, row.names=NULL,stringsAsFactors = FALSE))
#'data.frame': 5 obs. of 2 variables:
# $ X1: Factor w/ 1 level "d": 1 1 1 1 1
# $ X2: Factor w/ 1 level "d": 1 1 1 1 1
How to avoid this behaviour when the data.frame has many text columns?
I found the solution based on a comment by @thelatemail. It works for the actual version of zoo (Sept/2017). As @G. Grothendieck commented, the future versions of zoo will consider the stringsAsFactors = FALSE
argument.
str(base:::as.data.frame(coredata(dtfz),stringsAsFactors = FALSE))
#'data.frame': 5 obs. of 2 variables:
# $ X1: chr "d" "d" "d" "d" ...
# $ X2: chr "d" "d" "d" "d" ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With