Search code examples
rdataframedplyrrowmagrittr

Adding row in dplyr across a selected number of columns


While within dplyr workflow I would like to append a row across a selected number of columns.

Desired results

Starting with the mtcarsdata and applying function(s) with the goal of adding string "A" to columns 2:5 the one should arrive at the following results:

                    mpg  cyl disp  hp  drat wt    qsec   vs am   gear carb
                    NA     A A     A   A    NA    NA     NA NA   NA   NA
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2

The following criteria were met:

  • For the columns with available index in vars() call the "A" string was added
  • For the remaining columns the NA value was provided

Approach

require(dplyr)
mtcars %>%
  mutate_at(.cols = vars(2:5),
            .funs = add_row(. = "A", .before = 1))

Naturally, this results in an error message:

Error: Unsupported index type: NULL

Hence my question: how can I utilise add_row, or a similar approach, to force value across a set of columns initially passed via vars()?


Side notes

I don't mind doing this via rbind but I would like to keep my %>% workflow:

  1. %>% - receive object
  2. Add something across first row to columns x:y %>%
  3. Add something across first row to columns m:n %>%
  4. Other manipulations

Solution

  • Add the row then update:

    mtcars %>% 
      head %>%
      add_row(.before = 1) %>% 
      mutate_at(.cols = vars(2:5),
                funs(ifelse(is.na(.), "A", .)))
    
    #    mpg cyl disp  hp drat    wt  qsec vs am gear carb
    # 1   NA   A    A   A    A    NA    NA NA NA   NA   NA
    # 2 21.0   6  160 110  3.9 2.620 16.46  0  1    4    4
    # 3 21.0   6  160 110  3.9 2.875 17.02  0  1    4    4
    # 4 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
    # 5 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
    # 6 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
    # 7 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
    

    Note: This will add "A" to any row that has NAs.