Reputation: 4790
I have a matrix like this
df <- matrix(c(rep(1,3),rep(2,3)),nrow=3,ncol=2)
df:
[,1] [,2]
[1,] 1 2
[2,] 1 2
[3,] 1 2
I want to convert every cell value to YES
, if greater than 0, else NO
I understand that I can do this using
apply(df, 2, function(x) ifelse(x > 0, "Yes","No"))
However my matrix is very huge (million * 5000), and hence using apply takes insanely large time
I have also tried
df <- ifelse(df > 0, "Yes","No")
However even this takes a lot of time
Can I achieve better performance with this?
Upvotes: 2
Views: 800
Reputation: 38500
If your goal is to visually examine the matrix, and not use the contents, theThe symnum
function is designed for this use in particular. The Description section of ?symnum
says
Symbolically encode a given numeric or logical vector or array. Particularly useful for visualization of structured matrices, e.g., correlation, sparse, or logical ones.
symnum(df, cutpoints=c(-Inf, 0, Inf), symbols=c("no", "yes"))
[1,] yes yes
[2,] yes yes
[3,] yes yes
Upvotes: 0
Reputation: 81683
Here's one way to create the matrix:
df[] <- c("No", "Yes")[(df > 0) + 1]
The result:
[,1] [,2]
[1,] "Yes" "Yes"
[2,] "Yes" "Yes"
[3,] "Yes" "Yes"
Upvotes: 5