1

I want to add a column at specific position in r, but mutate (xx, .before = "exisiting column) doesn't work right:

starwars %>% mutate (new_column =  "Other", .before = 1)

# A tibble: 87 × 16
   name               height  mass hair_color    skin_color  eye_color birth_year sex    gender    homeworld species films     vehicles  starships ICP_type .before
   <chr>               <int> <dbl> <chr>         <chr>       <chr>          <dbl> <chr>  <chr>     <chr>     <chr>   <list>    <list>    <list>    <chr>      <dbl>
 1 Luke Skywalker        172    77 blond         fair        blue            19   male   masculine Tatooine  Human   <chr [5]> <chr [2]> <chr [2]> Other          1
 2 C-3PO                 167    75 NA            gold        yellow         112   none   masculine Tatooine  Droid   <chr [6]> <chr [0]> <chr [0]> Other          1
 3 R2-D2                  96    32 NA            white, blue red             33   none   masculine Naboo     Droid   <chr [7]> <chr [0]> <chr [0]> Other          1

It creates a ".before" column rather than adding the new column before the first column.

I tried add_column(), and it works ok. But I still want to know why it goes wrong. Thanks!

zx8754
  • 52,746
  • 12
  • 114
  • 209
Eleanor
  • 21
  • 3
  • 4
    Add sessionInfo, R version, dplyr version. This seems to work fine: `mtcars[1:3, 1:3] %>% mutate(x = "other", .before = 1)` with R version 4.2.2, dplyr_1.0.10. – zx8754 Jan 30 '23 at 14:16
  • 2
    It works for me as intended. Which `dplyr` version do you use? Have you maybe loaded another package that masks `mutate`? You could try using `dplyr::mutate` instead – starja Jan 30 '23 at 14:17
  • 2
    @r2evans yes, just noticed thanks, edited comment. But still works fine for me. – zx8754 Jan 30 '23 at 14:18
  • 2
    @zx8754 Agreed, it seems to be a problem specific to Eleanor's instance. – r2evans Jan 30 '23 at 14:41
  • Thanks all! It seems I got another package that masks mutate, dplyr::mutate works fine for me now. Much appreciated! – Eleanor Jan 30 '23 at 22:55

1 Answers1

2

You can try to use mutate and then relocate to specify the position:

starwars %>% 
  mutate(new_column =  "Other") %>% 
  relocate(new_column, .before =1)