prre72
prre72

Reputation: 717

R: Change Vector based on range conditions

I would like to change the vector elements based on conditions. For example: I have a vector v<-c(-3,5,-1,7,8,1,10,11) and I want to generate as a result the vector (-1,1,0,1,1,0,1,1) the conditions are

if the element is <-1 then set -1
if the element is >1 then set 1
otherwise 0

I could achieve this by using a serie of ifelse statements:

 v<-c(-3,5,-1,7,8,1,10,11)
    res<-rep(0,8)
    res<-ifelse(v<1,-1,res)
    res<-ifelse(v>1,1,res)

i think however there should be a more elegant and compact way to do this. any suggestions?

thanks

Upvotes: 0

Views: 1819

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81753

sign(v) * (abs(v) > 1)
# [1] -1  1  0  1  1  0  1  1

Upvotes: 1

Oleg Sklyar
Oleg Sklyar

Reputation: 10092

v[v >= -1 & v <= 1] = 0
v = sign(v)

Upvotes: 0

Related Questions