简体   繁体   中英

Change the column values withing dplyr pipes

I want to change the values of a column, which to be called by it's index , using pipe -

require(dplyr) 
mtcars[, 1] = 4 * mtcars[,2]

I was wondering if above calculation can be done using pipe

You can use magrittr and %<>% :

mtcars -> df1

library(dplyr) 
library(magrittr)

df1 %<>% 
  mutate_at(vars(1), list(~ df1[[2]] * 4))

#> # A tibble: 32 x 11
#>      mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
#>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1    24     6  160    110  3.9   2.62  16.5     0     1     4     4
#>  2    24     6  160    110  3.9   2.88  17.0     0     1     4     4
#>  3    16     4  108     93  3.85  2.32  18.6     1     1     4     1
#>  4    24     6  258    110  3.08  3.22  19.4     1     0     3     1
#>  5    32     8  360    175  3.15  3.44  17.0     0     0     3     2
#>  6    24     6  225    105  2.76  3.46  20.2     1     0     3     1
#>  7    32     8  360    245  3.21  3.57  15.8     0     0     3     4
#>  8    16     4  147.    62  3.69  3.19  20       1     0     4     2
#>  9    16     4  141.    95  3.92  3.15  22.9     1     0     4     2
#> 10    24     6  168.   123  3.92  3.44  18.3     1     0     4     4
#> # ... with 22 more rows

Another option could be:

mtcars %<>%
 mutate_at(vars(1), ~ !!select(., 2) %>% pull() * 4)

   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
1   24   6 160.0 110 3.90 2.620 16.46  0  1    4    4
2   24   6 160.0 110 3.90 2.875 17.02  0  1    4    4
3   16   4 108.0  93 3.85 2.320 18.61  1  1    4    1
4   24   6 258.0 110 3.08 3.215 19.44  1  0    3    1
5   32   8 360.0 175 3.15 3.440 17.02  0  0    3    2
6   24   6 225.0 105 2.76 3.460 20.22  1  0    3    1
7   32   8 360.0 245 3.21 3.570 15.84  0  0    3    4
8   16   4 146.7  62 3.69 3.190 20.00  1  0    4    2
9   16   4 140.8  95 3.92 3.150 22.90  1  0    4    2
10  24   6 167.6 123 3.92 3.440 18.30  1  0    4    4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM