Reputation: 1947
I have the problem following : Let's say we consider numbers from 1 to 102. I want to create four vectors a,b,c,d in such way :
Vector a takes value 1 if a=4k+1 and 0 otherwise
Vector b takes value 1 if a=4k+2 and 0 otherwise
Vector c takes value 1 if a=4k+3 and 0 otherwise
Vector d takes value 1 if a=4k and 0 otherwise
for some integer k.
My work so far
a<-b<-c<-d<-c()
for (i in 1:102)){
if (i%%4==1){a[i]<-1}
else (a[i]<-0)
}
for (i in 1:102){
if (i%%4==2){b[i]<-1}
else (b[i]<-0)
}
for (i in 1:102){
if (i%%4==3){c[i]<-1}
else (c[i]<-0)
}
for (i in 1:102){
if (i%%4==0){d[i]<-1}
else (d[i]<-0)}
}
Question
Is there any faster way to do that without using 4 loops ?
Upvotes: 0
Views: 37
Reputation: 145965
%%
is vectorized, so you don't need any loops. And ifelse
is a vectorized version of if(){}else{}
.
rem = 1:102 %% 4
a = ifelse(rem == 1, 1, 0)
b = ifelse(rem == 2, 1, 0)
c = ifelse(rem == 3, 1, 0)
d = ifelse(rem == 0, 1, 0)
The ifelse
makes it clear that you are getting a 1 or 0 output, but you can also do, e.g., a = as.integer(rem == 1)
to coerce the TRUE/FALSE directly to 1 and 0 instead of using ifelse
. It's a little more efficient, though perhaps a little less clear.
Upvotes: 4