Ramnik Bansal
2017-May-24 18:30 UTC
[R] Cause of error assigning NULL to element of a vector
What is the cause of the error below ?> y <- 1 > y[1] <- NULLError in y[1] <- NULL : replacement has length zero Thanks, Ramnik [[alternative HTML version deleted]]
Marc Schwartz
2017-May-24 18:51 UTC
[R] Cause of error assigning NULL to element of a vector
> On May 24, 2017, at 1:30 PM, Ramnik Bansal <ramnik.bansal at gmail.com> wrote: > > What is the cause of the error below ? > >> y <- 1 >> y[1] <- NULL > Error in y[1] <- NULL : replacement has length zero > > Thanks, > RamnikHi,> length(NULL)[1] 0 You are attempting to assign NULL, which is a zero length special object of its own kind, to a specific element in the vector object 'y' and that cannot be done. You can assign NULL to 'y': y <- NULL> yNULL> length(y)[1] 0 BUT, 'y' is not a vector in that case:> is.vector(y)[1] FALSE Nor can a vector contain multiple NULLs: y <- c(NULL, NULL, NULL)> yNULL> length(y)[1] 0 Similarly: y <- c(1, NULL, 1)> y[1] 1 1> length(y)[1] 2 Perhaps reviewing ?NULL as well as: https://cran.r-project.org/doc/manuals/r-release/R-lang.html#NULL-object might also provide some insights. Regards, Marc Schwartz
Jeff Newmiller
2017-May-24 19:38 UTC
[R] Cause of error assigning NULL to element of a vector
Perhaps it is worth pointing out (in case the OP thinks this is SQL) that the special value NA is used for "missing" in R. y[1] <- NA works just fine. -- Sent from my phone. Please excuse my brevity. On May 24, 2017 11:51:41 AM PDT, Marc Schwartz <marc_schwartz at me.com> wrote:> >> On May 24, 2017, at 1:30 PM, Ramnik Bansal <ramnik.bansal at gmail.com> >wrote: >> >> What is the cause of the error below ? >> >>> y <- 1 >>> y[1] <- NULL >> Error in y[1] <- NULL : replacement has length zero >> >> Thanks, >> Ramnik > >Hi, > >> length(NULL) >[1] 0 > >You are attempting to assign NULL, which is a zero length special >object of its own kind, to a specific element in the vector object 'y' >and that cannot be done. > >You can assign NULL to 'y': > >y <- NULL > >> y >NULL > >> length(y) >[1] 0 > > >BUT, 'y' is not a vector in that case: > >> is.vector(y) >[1] FALSE > > > >Nor can a vector contain multiple NULLs: > >y <- c(NULL, NULL, NULL) > >> y >NULL > >> length(y) >[1] 0 > > > >Similarly: > >y <- c(1, NULL, 1) > >> y >[1] 1 1 > >> length(y) >[1] 2 > > >Perhaps reviewing ?NULL as well as: > >https://cran.r-project.org/doc/manuals/r-release/R-lang.html#NULL-object > >might also provide some insights. > >Regards, > >Marc Schwartz > >______________________________________________ >R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see >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.