Rfreak
Rfreak

Reputation: 159

How to replace all negative values in vector by 0 in R

I have a randomly generated vector from a normal distribution with 50 elements

vector<-c(rnorm(50)) 

I want to change all negative values to 0 and positive values to 1

I used this function and indexing however then I do not get vector with 50 elements

vector[ vector< 0 ] <- 1
vector[ vector> 0 ] <- 0

How should I proceed?

Upvotes: 3

Views: 3594

Answers (2)

csgillespie
csgillespie

Reputation: 60452

Generate some data

x = rnorm(50)

then either

x = ifelse(x > 0, 1, 0)

or

x[x < 0] = 0 
x[x > 0] = 1

Or even better

  as.numeric (x>0)

However since the standard normal is symmetric about 0, why not simulate directly via

sample(0:1, 50, replace=TRUE)

Upvotes: 4

CAFEBABE
CAFEBABE

Reputation: 4101

The problem is that in the first query you replace all value smaller 0 by values larger zero so the trick is to switch

vector[ vector< 0 ] <- 1
vector[ vector> 0 ] <- 0

into

vector[ vector> 0 ] <- 0
vector[ vector< 0 ] <- 1

Note that you are also slightly biased towards 0 but that should only be marginal

Upvotes: 0

Related Questions