r - can dplyr package be used for conditional mutating? -


can mutate used when mutation conditional (depending on values of column values)?

this example helps showing mean.

structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4,  2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4,  5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4,  2, 2, 7, 5, 2)), .names = c("a", "b", "c", "d", "e", "f"), row.names = c(na,  8l), class = "data.frame")    b c d e f 1 1 1 6 6 1 2 2 3 3 3 2 2 3 3 4 4 6 4 4 4 4 6 2 5 5 5 2 5 3 6 3 3 6 2 6 2 7 6 7 7 7 7 5 2 5 2 6 5 8 1 6 3 6 3 2 

i hoping find solution problem using dplyr package (and yes know not code should work, guess makes purpose clear) creating new column g:

  library(dplyr)  df <- mutate(df, if (a == 2 | == 5 | == 7 | (a == 1 & b == 4)){g = 2},         if (a == 0 | == 1 | == 4 | == 3 |  c == 4){g = 3}) 

the result of code looking should have result in particular example:

  b c d e f  g 1 1 1 6 6 1 2  3 2 3 3 3 2 2 3  3 3 4 4 6 4 4 4  3 4 6 2 5 5 5 2 na 5 3 6 3 3 6 2 na 6 2 7 6 7 7 7  2 7 5 2 5 2 6 5  2 8 1 6 3 6 3 2  3 

does have idea how in dplyr? data frame example, data frames dealing larger. because of speed tried use dplyr, perhaps there other, better ways handle problem?

use ifelse

df %>%   mutate(g = ifelse(a == 2 | == 5 | == 7 | (a == 1 & b == 4), 2,                ifelse(a == 0 | == 1 | == 4 | == 3 |  c == 4, 3, na))) 

added: note in dplyr 0.5 there if_else function defined alternative replace ifelse if_else; however, note since if_else stricter ifelse (both legs of condition must have same type) na in case have replaced na_real_ .

df %>%   mutate(g = if_else(a == 2 | == 5 | == 7 | (a == 1 & b == 4), 2,                if_else(a == 0 | == 1 | == 4 | == 3 |  c == 4, 3, na_real_))) 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -