[R] Matrix to data.frame without factors

Mäkinen Jussi 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..

or 

"na.to.0" <- function(x)
{
	x <- as.matrix(x)	### Just to be sure
	x[is.na(x)] <- 0
	x <- data.frame(x)	### PROBLEM
	x
}

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:

> is.numeric(as.matrix(KUNTADATA[,15]))
[1] TRUE
> is.numeric(as.data.frame(as.matrix(KUNTADATA[,15])))
[1] FALSE
or
> is.numeric(data.frame(as.matrix(KUNTADATA[,15])))
[1] FALSE

as.numeric works of course but that's not to way to do well and error robust
code.

Please let me know if you have any idea how to avoid automatic factor or
character (last case) conversion.

Jussi
Analytics
State Treasury of Finland, Finance


PS.

version:
platform i386-pc-mingw32
arch     x86            
os       Win32          
system   x86, Win32     
status                  
major    1              
minor    4.1            
year     2002           
month    01             
day      30             
language R

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 mailing list