Can someone explain what’s happening in this example code? I have a function which does a calculation loop and as always, wanted to initialize my output vector instead of incrementing it each time thru the loop.
Rgames> library(Rmpfr)
Rgames> foo<-rep(NA,5)
Rgames> foo
[1] NA NA NA NA NA
Rgames> rfoo<-mpfr(rep(NA,5),20)
Rgames> rfoo
5 'mpfr' numbers of precision 20 bits
[1] NaN NaN NaN NaN NaN
Rgames> for(jj in 1:5) {
+ foo[jj]<- mpfr(jj,10)
+ rfoo[jj]<-mpfr(jj,10)
+ }
Rgames> rfoo
5 'mpfr' numbers of precision 10 bits
[1] 1 2 3 4 5
Rgames> foo
[[1]]
'mpfr1' 1
[[2]]
'mpfr1' 2
[[3]]
'mpfr1' 3
[[4]]
'mpfr1' 4
[[5]]
'mpfr1' 5
I don’t understand why, apparently, the existing non-mpfr vector foo is not only coerced to a list, but then each time through the loop, the new value is inserted into foo[jj] as a list, giving me an unpleasant “list of lists” . The mpfr vector rfoo does what I expected I’d get in both cases. (I checked, and if I do not initialize, and put something inside the loop like foo<-c(foo,mpfr(jj,10)) I do get a result equivalent to rfoo)
What’s happening here is the same thing that would happen if you were working with lists instead of
mpfrobjects. For example, as follows. I believe this makes sense because S4 objects are stored in a similar way to lists, but I’m not an S4 expert.I believe that what happens is that the original atomic vector gets coerced to a list to be able to include the object that you’ve asked to put there. I can’t find any documentation about that right here; I think it’s discussed in Chambers’s book but don’t have that at hand.
One can easily recreate this behavior using
S3methods as well; first theS3methods to create a new class:Here’s what happens if you start with an atomic vector:
and here’s what happens if you start with the
mynumvector: