[R] vectorization question

Alberto Murta amurta at ipimar.pt
Thu Aug 14 18:50:06 CEST 2003


Dear all

I recently noticed the following error when cohercing a data.frame into a 
matrix:

> example <- matrix(1:12,4,3)
> example <- as.data.frame(example)
> example$V4 <- 0
> example
  V1 V2 V3 V4
1  1  5  9   0
2  2  6 10  0
3  3  7 11  0
4  4  8 12  0
> example <- as.matrix(example)
Error in as.matrix.data.frame(example) : dim<- length of dims do not match the 
length of object

However, if the column to be added has the right number of lines, there's no 
error:

> example <- matrix(1:12,4,3)
> example <- as.data.frame(example)
> example$V4 <- rep(0,4)
> example
  V1 V2 V3 V4
1  1  5  9  0
2  2  6 10  0
3  3  7 11  0
4  4  8 12  0
> example <- as.matrix(example)
> example
  V1 V2 V3 V4
1  1  5  9  0
2  2  6 10  0
3  3  7 11  0
4  4  8 12  0

Shouldn't it work well both ways? I checked the attributes and dims of the 
data frame and they are the same in both cases. Where's the difference that 
originates the error message?
Thanks in advance

Alberto

platform i686-pc-linux-gnu
arch     i686             
os       linux-gnu        
system   i686, linux-gnu  
status                    
major    1                
minor    7.1              
year     2003             
month    06               
day      16               
language R    


-- 
                                         Alberto G. Murta
Institute for Agriculture and Fisheries Research (INIAP-IPIMAR) 
Av. Brasilia, 1449-006 Lisboa, Portugal | Phone: +351 213027062
Fax:+351 213015948 | http://www.ipimar-iniap.ipimar.pt/pelagicos/




More information about the R-help mailing list