Search code examples
rdataframedplyrpipeassign

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


Solution

  • 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