[R] why should you set the mode in a vector?

Peter Dalgaard p.dalgaard at biostat.ku.dk
Sat Oct 30 00:22:42 CEST 2004


Joel Bremson <joel3000 at gmail.com> writes:

> Hi all,
> 
> If I write
> 
> v = vector(mode="numeric",length=10)
> 
> I'm still allowed to assign non-numerics to v.

Not without changing the mode of v or the right hand side:

> v = vector(mode="numeric",length=10)
> v[3] <- T
> v
 [1] 0 0 1 0 0 0 0 0 0 0
> v[4] <- "foo"
> v
 [1] "0"   "0"   "1"   "foo" "0"   "0"   "0"   "0"   "0"   "0"

[Basically, there's a hierarchy: 

   logical < integer < double < complex < character

and coercion is guaranteed to work from "smaller" to "larger" modes,
but not the other way. In assignments, both sides are coerced to the
larger of the two modes before the actual assignment.]

 
> Furthermore, R figures out what kind of vector I've got anyway
> when I use the mode() function.
> 
> So what is it that assigning a mode does?

Well, it sets the mode so that R doesn't have to change it later....

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list