r - alternative for loop in data frame -


i facing problem amount of time needed run code. basically, have several columns key value in last column (that identify mean in reproducible example). want 1 when below value , 2 when above.

is there easier way this?

a <- c(1,3,5,6,4) b <- c(10,4,24,5,3) df <- data.frame (a,b) df$mean <- rowmeans (df)  (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 in advance

you can do,

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

which gives,

  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 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -