yrx1702
yrx1702

Reputation: 1641

Replace matrix in list using logical expression

Assume you have a list of matrices A and B such that

A <- matrix(0,3,3)
B <- matrix(0,3,3)
mat.list <- list(A,B)

and you want to replace some of these matrices with a matrix C in the list using a logical vector. My attempt would have been the following:

replace <- c(T,F)   #logical vector for replacement
C <- matrix(1,3,3)  #replacement matrix
mat.list[replace] <- mat.list #my attempt

However, that results in a warning and no replacement takes place:

Warning message:
In mat.list[replace] = C :
  number of items to replace is not a multiple of replacement length

In a way, this was unexpected, at least to me. I suspect the combination of a logical vector and lists is probably not ideal here? Can we make this work using a logical vector that is the same length as the list has elements?

Upvotes: 0

Views: 20

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101317

You can try the replacement approaches like below

mat.list[replace] <- list(C)

or

mat.list[[which(replace)]] <- C

Upvotes: 2

alan ocallaghan
alan ocallaghan

Reputation: 3038

A <- matrix(0,3,3)
B <- matrix(0,3,3)
mat.list <- list(A,B)
mat.list
#> [[1]]
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    0    0    0
#> 
#> [[2]]
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    0    0    0

replace <- c(TRUE, FALSE)  
C <- matrix(1,3,3)  
mat.list[which(replace)] <- list(C)

mat.list
#> [[1]]
#>      [,1] [,2] [,3]
#> [1,]    1    1    1
#> [2,]    1    1    1
#> [3,]    1    1    1
#> 
#> [[2]]
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    0    0    0

By the way, don't use T and F in your code, or somebody will do this to you:

T <- FALSE
F <- TRUE
A <- matrix(0,3,3)
B <- matrix(0,3,3)
mat.list <- list(A,B)
mat.list
#> [[1]]
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    0    0    0
#> 
#> [[2]]
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    0    0    0

replace <- c(T,F)  
C <- matrix(1,3,3)  
mat.list[which(replace)] <- list(C)

mat.list
#> [[1]]
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0
#> [3,]    0    0    0
#> 
#> [[2]]
#>      [,1] [,2] [,3]
#> [1,]    1    1    1
#> [2,]    1    1    1
#> [3,]    1    1    1

Upvotes: 1

Related Questions