Home > front end >  Make a new vector according to a given vector in R
Make a new vector according to a given vector in R

Time:08-15

Imagine I give you a vector like a = (8 - 2) - (7 - 1) which can be simplified as z = (8 - 2 - 7 1).

Now imagine I give you a vector consisting of nine 0s, b = c(0,0,0,0,0,0,0,0,0).

Can R turn a to the following vector desired_output = c(1,-1,0,0,0,0,-1,1,0)?

The logic

The numbers in a are locations of elements in b (ex. 8 in a means 8th element in b).

The logic is to assign either 1 or -1 for the elements indicated in a based on their sign and assign 0 to all other elements in b so to get the desired_output.

CodePudding user response:

I don't entirely understand your problem setup — in R terms, a = (8 - 2) - (7 - 1) is an expression rather than a vector — but here's a start:

b <- rep(0,9)
a <- c(8, -2, -7, 1)
b[abs(a)] <- sign(a)
## [1]  1 -1  0  0  0  0 -1  1  0

CodePudding user response:

  • We can use for loop
for(i in a){
    if(i > 0) b[i] <- 1
    else b[abs(i)] <- -1
}
  • Output
[1]  1 -1  0  0  0  0 -1  1  0
  • Data
a <-  c(8 ,- 2 ,- 7 ,1)
b <- c(0,0,0,0,0,0,0,0,0)
  • Related