[R] Why does `[<-.matrix` not exist in base R
peter dalgaard
pd@|gd @end|ng |rom gm@||@com
Sun Nov 24 15:47:02 CET 2019
The subject is misguided. It is not a problem to assign to a subset of columns.
The issue is that the assignment operation does not want to _expand_ the matrix automatically upon seeing an out-of-bounds index. E.g.:
> M <- matrix(0,2,2)
> M[,3]<-1
Error in `[<-`(`*tmp*`, , 3, value = 1) : subscript out of bounds
> M[,2]<-1
> M
[,1] [,2]
[1,] 0 1
[2,] 0 1
You can, however, do things like this:
> M <- M[,c(1,2,2)]
> M[,3]<-3
> M
[,1] [,2] [,3]
[1,] 0 1 3
[2,] 0 1 3
-pd
> On 23 Nov 2019, at 17:58 , David Disabato <ddisab01 using gmail.com> wrote:
>
> Whenever going from working with a data.frame to a matrix, I get annoyed
> that I cannot assign and subset at the same time with matrices - like I can
> with data.frames.
>
> For example, if I want to add a new column to a data.frame, I can do
> something like `myDataFrame[, "newColumn"] <- NA`.
>
> However, with a matrix, this syntax does not work and I have to use a call
> to `cbind` and create a new object. For example, `mymatrix2 <-
> cbind(mymatrix, "newColumn" = NA)`.
>
> Is there a programming reason that base R does not have a matrix method for
> `[<-` or is it something that arguably should be added?
>
> --
> David J. Disabato, Ph.D.
> Postdoctoral Research Scholar
> Kent State University
> ddisab01 using gmail.com
>
> Email is not a secure form of communication as information and
> confidentiality cannot be guaranteed. Information provided in an email is
> not intended to be a professional service. In the case of a crisis or
> emergency situation, call 911.
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using 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.
--
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes using cbs.dk Priv: PDalgd using gmail.com
More information about the R-help
mailing list