Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid (as)data.frame change data to factors when converting from zoo object

Tags:

dataframe

r

zoo

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?

like image 572
Robert Avatar asked Oct 17 '22 06:10

Robert


1 Answers

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" ...
like image 194
Robert Avatar answered Oct 20 '22 09:10

Robert