r - Avoid (as)data.frame change data to factors when converting from zoo object -
if have data.frame
numeric columns conversion without problems, 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 have data.frame
text columns converted factors, when setting stringsasfactors = false
dtf=data.frame(matrix(rep("d",10),ncol=2),stringsasfactors = false) #str(dtf) dtfz <- zoo(dtf) #class(dtfz) #dtfz
all following convert strings 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 avoid behaviour when data.frame has many text columns?
i found solution based on comment @thelatemail. works actual version of zoo (sept/2017). @g. grothendieck commented, future versions of zoo consider 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" ...
Comments
Post a Comment