Doron Howard
Doron Howard

Reputation: 31

turning the non-zeros of a vector into 1's

suppose I create the following vector:

x = c(1, 3, 5, 0, 7, 8, 0, 4, 5, 0, 8)
x

I want to turn the non-zeros into ones:

for (   i in 1:length(x)   ){
if (x[i]!=0)   x[i] = 1}
x

This works fine, but I was wondering if anyone out there can think of a mathematical way of doing this operation instead of using the if statement.

Upvotes: 2

Views: 59

Answers (4)

Carl Witthoft
Carl Witthoft

Reputation: 21492

The official code-nerd way is y <- !!x :-)

Upvotes: 3

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

Logically, just do:

as.logical(x) + 0L
#[1] 1 1 1 0 1 1 0 1 1 0 1

Upvotes: 2

Sam Firke
Sam Firke

Reputation: 23004

Is this more mathematical?

x = c(1, 3, 5, 0, 7, 8, 0, 4, 5, 0, 8)
ceiling(x/.Machine$integer.max)

[1] 1 1 1 0 1 1 0 1 1 0 1 

Upvotes: 1

Nikos
Nikos

Reputation: 3297

You are overcomplicating it. No need for an rbind, use c

x = c(1, 3, 5, 0, 7, 8, 0, 4, 5, 0, 8);
x[x!=0]=1;

Upvotes: 4

Related Questions