R Question

alternative for loop in data frame

I am facing a problem with the amount of time needed to run my code. Basically, I have several columns a key value in the last column (that I identify as the mean in the reproducible example). I want it to be 1 when it is below the value and 2 when it is above.

Is there an easier way to do this?

a <- c(1,3,5,6,4)
b <- c(10,4,24,5,3)
df <- data.frame (a,b)
df$mean <- rowMeans (df)

for (i in 1:5){
df[i,1:2] [df[i,1:2]<df$mean[i]] <- 1
df[i,1:2] [df[i,1:2]>df$mean[i]] <- 2
}


Thank you in advance

Answer Source

You can simply do,

df[1:2] <- (df[1:2] > df$mean) + 1 #removed as.integer as per @akrun's comment

Which gives,

  a b mean
1 1 2  5.5
2 1 2  3.5
3 1 2 14.5
4 2 1  5.5
5 2 1  3.5