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

Tony Plate tplate at acm.org
Sat Oct 30 00:23:11 CEST 2004


It's useful when you need to be certain of the mode of a vector.  One such 
situation is when you are about to call a C-language function using the 
.C() interface.  As you point out, some assignments (even just to vector 
elements) can change the mode of the entire vector.  This is why it's 
important to check the mode of vectors passed to external language 
functions immediately before the call.

As to what assigning the mode does, it specifies (or changes, if necessary) 
the underlying type of storage of the vector.  In R, all the elements in a 
vector have the same storage mode.  In the example below, the storage is 
initial as double-precision floats, but after the assignment of character 
data to element 2, the vector is stored as character data (with suitably 
coerced values of the other elements).  After assignment of list data to 
element 1, the entire vector becomes a list (i.e., a vector of pointers to 
general objects).  [The terminology I'm using here is a little loose, but 
someone please correct me if it is outright wrong.]  Finally, the assigning 
of mode "numeric" to the list fails because not all elements can be 
coerced.  (And I'm not sure why the last assignment succeeds and produces 
the results it does.)

 > v <- vector(mode="numeric",length=4)
 > v[3:4] <- 3:4
 > storage.mode(v)
[1] "double"
 > v[2] <- "foo"
 > v
[1] "0"   "foo" "3"   "4"
 > storage.mode(v)
[1] "character"
 >
 > v[1] <- list(1:3)
 > v
[[1]]
[1] 1 2 3

[[2]]
[1] "foo"

[[3]]
[1] "3"

[[4]]
[1] "4"

 > mode(v) <- "numeric"
Error in as.double.default(list(as.integer(c(1, 2, 3)), "foo", "3", "4")) :
         (list) object cannot be coerced to double
 > x <- v[2:4]
 > mode(x) <- "numeric"
 > x
[1] NA NA NA
 >

-- Tony Plate

At Friday 03:41 PM 10/29/2004, Joel Bremson wrote:
>Hi all,
>
>If I write
>
>v = vector(mode="numeric",length=10)
>
>I'm still allowed to assign non-numerics to v.
>
>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?
>
>Joel
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html




More information about the R-help mailing list