Reputation: 31
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
Reputation: 31161
Logically, just do:
as.logical(x) + 0L
#[1] 1 1 1 0 1 1 0 1 1 0 1
Upvotes: 2
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
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