R: Convert Matrix to YES, NO dataframe

Home / Uncategorized / R: Convert Matrix to YES, NO dataframe

Question:
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?


Answer:
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"
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *