Ketty
Ketty

Reputation: 851

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
                 }
         }
   }

*

Upvotes: 3

Views: 196

Answers (1)

akrun
akrun

Reputation: 887901

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))

Upvotes: 5

Related Questions