[R] Matrix to data.frame without factors
Jussi.Makinen at valtiokonttori.fi
Fri Apr 12 10:12:47 CEST 2002
Hello and thank you dear R-people in advance.
This is quite basic question but which I have confronted occasionally and
get over it without satisfying solution. The question is about factors, this
time I would just like convert a data.frames NA-terms to 0 and get a
data.frame as a result. There might be a way to do that inside of the
data.frame but I think that it might be overcomplicated and possible slow.
With matrix it is easy and clean:
X <- (ifelse(is.na(X), 0, X)) ### Applying data.frames yields list..
"na.to.0" <- function(x)
x <- as.matrix(x) ### Just to be sure
x[is.na(x)] <- 0
x <- data.frame(x) ### PROBLEM
So the problem comes when converting the result to a data.frame (this is
sometimes also a problem when importing data.frame!). All character columns
goes to factors as documented in help. That's something one can avoid by
using I() or later call type.convert (convert.col.type in Splus if I can
recall) but somehow I think that there should be a way to make it easier. At
least in a case when converting data.frame to matrix and back to data.frame.
The other but related question is odd. This time I have numeric col in a
data.frame (at least it should be) which I have fetched from Excel through
RODBC (it's great). But when I'm trying to convert Na to 0 as a side effect
these columns get converted to characters:
as.numeric works of course but that's not to way to do well and error robust
Please let me know if you have any idea how to avoid automatic factor or
character (last case) conversion.
State Treasury of Finland, Finance
system x86, Win32
Platform is Windows NT4 (not my choice..)
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
More information about the R-help