[R] possibly Error in R version 2.12.1 (2010-12-16)
peter dalgaard
pdalgd at gmail.com
Fri Feb 3 14:01:02 CET 2012
On Feb 2, 2012, at 21:24 , Frank Schwidom wrote:
> Hi,
>
> the following Code demonstrates an possibly Error in R
> (or you can explain me, why this happens, thanks in advance)
Looks like an effect of lazy evaluation: The value of i is not evaluated until after the loop has ended, at which point it will be 2. This is a feature, not an error, even if it confuses people at times...
-pd
>
> Code:
>
> #####################################
>
> testClass <- function( stackData= c())
> {
>
> list(
>
> write= function( ...)
> {
> sChain= ""
> for( s in c( stackData, ...))
> {
> sChain= paste( sChain, '"', sub( '"', '\\\\"', s), '"', sep, sep='')
> }
> write( sChain, fHandle, append=TRUE)
> },
>
> stackIt1 = function( ...)
> {
> testClass( stackData= c( stackData, ...))
> },
>
> stackIt2 = function( ...)
> {
> tmp= c( stackData, ...)
> testClass( stackData= tmp)
> },
>
> getStack = function()
> {
> stackData
> },
>
> NULL
> )
> }
>
> to1= testClass()
>
> for( i in 4:2)
> {
> to1= to1$stackIt1( i)
> }
>
> print( all( rep( 2, 3) == to1$getStack())) # error!
>
> to2= testClass()
>
> for( i in 4:2)
> {
> to2= to2$stackIt2( i)
> }
>
> print( all( 4:2 == to2$getStack())) # correct!
>
> # what ist the difference between stackIt1 and stackIt2?
> # (error appears only by using an for loop)
>
> "
>> version
> _
> platform i486-pc-linux-gnu
> arch i486
> os linux-gnu
> system i486, linux-gnu
> status
> major 2
> minor 12.1
> year 2010
> month 12
> day 16
> svn rev 53855
> language R
> version.string R version 2.12.1 (2010-12-16)
>
> Regards
> "
>
> ##################################### End of Code
>
> written in an R-File and called per source( '<Fname>.R')
> shows 2 subsequent outputs of 'TRUE', which is not ok
> in my mind
>
> Thanks for your attention
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Peter Dalgaard, Professor
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com
More information about the R-help
mailing list