indexing - R conditional replacement data frame values -


i want update dataframe column (df$d) result of mathematical operation on 1 or more other columns (df$b, df$c), conditional on value of column (df$a).

set.seed(55) df <- data.frame(a = rnorm(10), b = rnorm(10), c = rnorm(10), d = 0) df$d[df$a > 0] <- df$b[df$a > 0] / df$c[df$a > 0] 

the third line produces expected values df$d. there way write more succinctly? i'm interested in options not require me repeat logical index.

for example, style of expression works in python/pandas , requires 1 instance of '[df$a > 0]' on left-hand side of assignment operator:

df$d[df$a > 0] <- df$b / df$c 

thank , advice.

use data.table instead , life better:

library(data.table) dt = data.table(df) # or construct same way: dt = data.table(a = rnorm(10),...)  dt[a > 0, d := b/c] 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -