Applying Loop to Elements of a Matrix (R)

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've made a new array using the following rules:

  • If the value is less than or equal to 0.1 transform 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 it becomes 3
  • If the value is greater than 0.7 and less than or equal to 0.9 it becomes 4
  • The rest transforms 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?

    
asked by anonymous 01.07.2014 / 16:01

1 answer

3

Use the cut function to encode the values according to the range they fit into, 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 of labels )

    
02.07.2014 / 02:57