R conditional replacement data frame values
I want to update a dataframe column (df$d) with the result of a
mathematical operation on one or more other columns (df$b, df$c),
conditional on the value of another 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 the expected values for df$d. Is there a way to
write this more succinctly? I'm especially interested in options that do
not require me to repeat the logical index.
For example, this style of expression works in Python/Pandas and requires
only one instance of '[df$a > 0]' on the left-hand side of the assignment
operator:
df$d[df$a > 0] <- df$b / df$c
Thank you for any and all advice.
No comments:
Post a Comment