Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorize double loops in R

I am new to R and am trying to vectorize my codes below.

What is a better way to do this? Thanks so much!

*

l_mat <- data.frame(matrix(ncol = 4, nrow = 4))
datax <- data.frame("var1"= c(1,1,1,1), "Var2" = c(2,2,2,2), "Var3"=c(3,3,3,3), "Var4"=c(4,4,4,4))
for (i in 1:4) {
      for (j in 1:4) {
             if (datax[i, 2] == datax[j, 2]) {
                   l_mat[i, j] <- 100
               } else {
                     l_mat[i, j] <- 1
                 }
         }
   }

*

like image 300
Ketty Avatar asked Mar 16 '26 23:03

Ketty


1 Answers

It can be better done with outer. As we are checking if all the values in the second column against itself, create the logical expression with outer, convert it to a numeric index and then replace the values with 1 or 100

out <- 1 + (outer(datax[,2], datax[,2], `==`))
out[] <- c(1, 100)[out]

Or in a single line

ifelse(outer(datax[,2], datax[,2], `==`), 100, 1)

Or use a variation with pmax and outer

do.call(pmax, list(outer(datax[,2], datax[,2], `==`) * 100, 1))
like image 189
akrun Avatar answered Mar 18 '26 14:03

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!