How to multiply by 2 all the rows that meet condition mpg*cyl=126
and add the result in another column at the end? Those that meet the condition will add the result and those that not will put a 0 as a result.
Hi! It sounds like you're trying to multiply the subset filter(mtcars, mpg * cyl == 126)
by 2, zero-fill the subset filter(mtcars, mpg * cyl != 126)
, and preserve the existing columns in mtcars
.
library(tidyverse)
set.seed(321)
group_nest(mtcars, .p = mpg * cyl == 126) %>%
transmute(data,
map_if(data, .p,
~ .x * 2,
.else = ~ mutate_all(.x, ~ 0))) %>%
unnest() %>%
sample_n(5)
#> # A tibble: 5 x 22
#> mpg cyl disp hp drat wt qsec vs am gear carb mpg1
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 21 6 160 110 3.9 2.62 16.5 0 1 4 4 42
#> 2 21.4 4 121 109 4.11 2.78 18.6 1 1 4 2 0
#> 3 19.2 6 168. 123 3.92 3.44 18.3 1 0 4 4 0
#> 4 21 6 160 110 3.9 2.88 17.0 0 1 4 4 42
#> 5 17.3 8 276. 180 3.07 3.73 17.6 0 0 3 3 0
#> # … with 10 more variables: cyl1 <dbl>, disp1 <dbl>, hp1 <dbl>,
#> # drat1 <dbl>, wt1 <dbl>, qsec1 <dbl>, vs1 <dbl>, am1 <dbl>,
#> # gear1 <dbl>, carb1 <dbl>
Created on 2019-03-20 by the reprex package (v0.2.1)