Applying Loop to Elements of a Matrix (R)

Asked

Viewed 250 times

2

Be the matrix below created from the Command

simu_matrix <- matrix(runif(25,0,1),nrow=5,ncol=5)

    V1          V2          V3          V4          V5
1   0.07357303  0.45524021  0.9352829   0.60466424  0.4725541
2   0.51018615  0.46044203  0.6975768   0.43135240  0.7924976
3   0.60578062  0.94756261  0.4729004   0.88412092  0.2425650
4   0.16868889  0.34543686  0.1628527   0.05012683  0.7320737
5   0.76139364  0.08249016  0.1384000   0.23841682  0.5925934

I turned it into a new matrix using the following rules :

  • If the value is less than or equal to 0.1 turns into 1
  • If Value is greater than 0.1 and less than or equal to 0.4 turns into 2
  • If the value is greater than 0.4 and less than or equal to 0.7 turns into 3
  • If the value is greater than 0.7 and less than or equal to 0.9 turns into 4
  • The rest turns into 5

The resulting Matrix was :

    V1  V2  V3  V4  V5
1   1   3   5   3   3
2   3   3   3   3   4
3   3   5   3   4   2
4   2   2   2   1   4
5   4   1   2   2   3

The code used was :

simu_bets <- apply(simu_matrix,2,function(x) 
ifelse(x<0.1,1,
       ifelse(x>0.1 & x<=0.4,2,
              ifelse(x>0.4 & x<=0.7,3,
                     ifelse(x>0.7 & x<=0.9,4,5)))))

My question is, is there a better way to get the same result ?

1 answer

3


Use the function cut to encode the values according to the range they fit, and then convert the result to number:

c <- cut(simu_matrix, breaks=c(0.0, 0.1, 0.4, 0.7, 0.9, 1.0))
matrix(as.numeric(c), nrow=5)

Workaround

apply(simu_matrix, 1, 
  function(x) as.numeric(
    cut(x, breaks=c(0.0, 0.1, 0.4, 0.7, 0.9, 1.0), labels=1:5)))

(thanks to Carlos Cinelli for the tip from labels)

  • 1

    Very good, I would only add the following information. The way it works is because the question wants to convert in order of breaks. But if he wanted to put arbitrary numbers or texts in place of numbers from 1 to 5, just use the Labels parameter and use as.character when converting. For example, put in reverse order c <- cut(simu_matrix, breaks=c(0.0, 0.1, 0.4, 0.7, 0.9, 1.0), labels=5:1);&#xA;matrix(as.numeric(as.character(c)), nrow=5)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.