I have the following logical
matrix:-
k <- matrix(c(T,T,F,F,T,F,T,F,T,T,F,F,T,F,T,F,T,T,T,T,F,F,F,F,F), 5)
However, when I do the following:-
z <- as.integer(k)
I get an integer
vector rather than an integer
matrix:-
[1] 1 1 0 0 1 0 1 0 1 1 0 0 1 0 1 0 1 1 1 1 0 0 0 0 0
I want it to get a matrix like following:-
k <- matrix(c(1,1,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,1,1,0,0,0,0,0), 5)
Thanks in advance.
CodePudding user response:
We may need to use []
to keep the dim intact
z <- k
z[] <- as.integer(k)
Or another option is to do the dim
assignment
z <- as.integer(k)
dim(z) <- dim(k)
Or without doing the dim
changes, can just multiply by 1
to coerce to numeric
z <- k * 1
CodePudding user response:
Use unary
:
k
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 0 0 0 0
## [2,] 1 1 0 1 0
## [3,] 0 0 1 1 0
## [4,] 0 1 0 1 0
## [5,] 1 1 1 1 0
CodePudding user response:
k <- matrix(c(T,T,F,F,T,F,T,F,T,T,F,F,T,F,T,F,T,T,T,T,F,F,F,F,F), 5)
res <- k
res
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 1 0 0 0 0
#> [2,] 1 1 0 1 0
#> [3,] 0 0 1 1 0
#> [4,] 0 1 0 1 0
#> [5,] 1 1 1 1 0
Created on 2021-10-04 by the reprex package (v2.0.1)