miciobauciao
miciobauciao

Reputation: 85

R avoid a for loop using an apply

I have a problem like this. I managed it using this kind of statement but it's to slow. Can I improve the performance using an apply function?

x<-matrix(sample(1:100,40),20,2)
x<-as.data.frame(x)
for ( i in 1:nrow(x))
{
  if ( x[i,1]>x[i,2] ){
    x[i,3]<-1
  } else {
    x[i,3]<-0
  }
}

Upvotes: 1

Views: 60

Answers (1)

Hong Ooi
Hong Ooi

Reputation: 57696

You don't need explicit or implicit looping; just use ifelse:

x[, 3] <- ifelse(x[, 1] > x[, 2], 1, 0)

And in fact, you can simplify this even further:

x[, 3] <- x[, 1] > x[, 2]

This will create a column that is logical rather than numeric, but for most purposes that's close enough. If not, you can convert the logical back to numeric:

x[, 3] <- as.numeric(x[, 1] > x[, 2])

Upvotes: 2

Related Questions