# [R] efficiently replacing values in a matrix

Matthew Keller mckellercran at gmail.com
Fri Apr 18 20:18:27 CEST 2008

```Nanmdi,

I think this is simply because a lot of time is taken transforming the
matrix from logical (default when you create it) to numeric (when you
add the number to [1,1]. If you do the same thing again to [1,2], it
is done instantaneously:
> a <- matrix(nrow=10000,ncol=10000)
> system.time(a[1,1] <- 1903908.80385)
user  system elapsed
10.000   0.781  10.755
>
> system.time(a[1,2] <- 1903908.80385)
user  system elapsed
0       0       0

By the way Rolf - I didn't see your full response last time through. I
do know the difference between a matrix and a data.frame, thank you
very much.

On Fri, Apr 18, 2008 at 11:11 AM, Nnamdi <nnamdii at yahoo.com> wrote:
>
>  Still it is pretty slow when entering values into a large matrix. Case in
>  point:
>
>  > a <- matrix(nrow=10000,ncol=10000)
>  > system.time(a[1,1] <- 1903908.80385)
>    user  system elapsed
>   30.840   6.226  41.416
>  > is.matrix(a)
>  [1] TRUE
>
>  Is there a better way to enter values into large matrices? If I have to
>  spend 41 secs each time I enter into a cell and I have 10000x10000 cells to
>  enter that is impractical!
>
>  --Nnamdi
>
>
>  Rolf Turner-3 wrote:
>  >
>  >
>  > On 17/04/2008, at 9:33 AM, Charles C. Berry wrote:
>  >
>  >       <snip>
>  >
>  >> I'll lay odds that Matthew's 'matrix' is actually a data.frame, and
>  >> I'll not be surprised if the columns are factors.
>  >
>  >       <snip>
>  >
>  > I suspect that you're right.
>  >
>  > ***Why*** can't people distinguish between data frames and matrices?
>  > If they were the same <expletive deleted> thing, there wouldn't be two
>  > different terms for them, would there?
>  >
>  >       cheers,
>  >
>  >               Rolf Turner
>  >
>  > ######################################################################
>
> > Attention:\ This e-mail message is privileged and confid...{{dropped:9}}
>  >
>  > ______________________________________________
>  > R-help at r-project.org mailing list
>  > https://stat.ethz.ch/mailman/listinfo/r-help
>  > http://www.R-project.org/posting-guide.html
>  > and provide commented, minimal, self-contained, reproducible code.
>  >
>  >
>
>  --
>  View this message in context: http://www.nabble.com/efficiently-replacing-values-in-a-matrix-tp16732795p16763578.html
>  Sent from the R help mailing list archive at Nabble.com.
>
>
>
>  ______________________________________________
>  R-help at r-project.org mailing list
>  https://stat.ethz.ch/mailman/listinfo/r-help
>  and provide commented, minimal, self-contained, reproducible code.
>

--
Matthew C Keller
Asst. Professor of Psychology