Meli
Meli

Reputation: 31

loop: Replacing value at a certain position

I have one matrix and one vector and want to change the values at the position of the matrix where the value in the vector is negative.

x <- c(1,-5,4,-8,9)

X <- matrix(c(5,7,3,
              -5,6,8,
              9,-6,4,
              2,-1,-3,
              5,2,4),byrow=TRUE, nrow=5)

for all the values of x which are i<0 take the position and multiply at this position in X the whole row with -1

This should be the result:

X2 <- matrix(c(5,7,3,
               5,-6,-8,
               9,-6,4,
               -2,1,3,
               5,2,4),byrow=TRUE, nrow=5)

this is what I tried, but it doesn't work:

if (x[i] > 0) {
  X[i, ] <- (- X[i, ])
}
print(X)

Upvotes: 2

Views: 65

Answers (3)

s_baldur
s_baldur

Reputation: 33498

What about this?

for (i in seq_along(x)) {
  if (x[i] < 0) {
    X[i, ] <- -X[i, ]
  }
}

print(X)
     [,1] [,2] [,3]
[1,]    5    7    3
[2,]    5   -6   -8
[3,]    9   -6    4
[4,]   -2    1    3
[5,]    5    2    4

Data

x <- c(1,-5, 4, -8, 9)
X <- matrix(
  c(5, 7, 3, -5, 6, 8, 9,-6, 4, 2, -1, -3, 5, 2, 4),
  byrow=TRUE,
  nrow=5
)

Upvotes: 0

Sean Lin
Sean Lin

Reputation: 815

I don't think you need a loop, just try this.

X * sign(x)

Upvotes: 6

Mislav
Mislav

Reputation: 1563

Try this:

x <- c(1,-5,4,-8,9)

X <- matrix(c(5,7,3,
              -5,6,8,
              9,-6,4,
              2,-1,-3,
              5,2,4),byrow=TRUE, nrow=5)

x
X
for(i in 1:length(x)){
  if (x[i] < 0) {
    X[i, ] <- - X[i, ]
  }
}
X

Upvotes: 0

Related Questions