Home > Blockchain >  Using a for loop and if-statement to compare two matrices (x and y) to create new column in one of t
Using a for loop and if-statement to compare two matrices (x and y) to create new column in one of t

Time:03-10

I have two matrices (x and y) - reproduced using below code.

 x <- structure(c(0.11, 0.91, 1.28, 0.32, 0.23, 0.45, 1.17, 0.68, 0.85, 
        0.46), .Dim = c(10L, 1L))
            y <- structure(c(3, 5, 7, 9, 11, 13, 18, 20, 22, 26), .Dim = c(10L, 
        1L))

What I am trying to do is use the following For and if/else combination. What I am trying to do is IF value in x is <0.3, a new matrix column is created in y [i,2] that states either 0 (False, value in x isn't less than 0.3) or 1 (True, value in x is greater than 0.3)

I keep getting the error code "Error in y[i, 2] : subscript out of bounds"

for (i in 1:10){
if (x[i,1]<0.3){
    y[i,2] == 0
} else {
    y[i,2] == 1
}
}

Please don't suggest alternative ways (i.e., not using for/if/else) because this is the way that I have been told is required for this project.

CodePudding user response:

You can't add this to y, without first adding a column and putting something in it the same length as y is already. You can make a new vector and bind them. (Which would probably be easier.)

# an empty vector to put it in
z = vector(length = 10)

# the loop 
for (i in 1:10){
  if (x[i, 1] < 0.3){
    z[i] = TRUE
  } else {
    z[i] = FALSE
  }
}

z
# [1]  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE

You could make this even easier.


Updated


I completely overlooked the power of ifelse all by itself.

# vectorize 
z <- ifelse(x < .3, T, F)) 
z

# join with y
y <- cbind(y, z) 

CodePudding user response:

You can try the code below

> cbind(y, x >= 0.3)
      [,1] [,2]
 [1,]    3    0
 [2,]    5    1
 [3,]    7    1
 [4,]    9    1
 [5,]   11    0
 [6,]   13    1
 [7,]   18    1
 [8,]   20    1
 [9,]   22    1
[10,]   26    1
  • Related