9

Building on this question: dplyr: how to reference columns by column index rather than column name using mutate?

I want to mutate using column indexes for both the source and the destination of the mutate:

iris %>% head %>% mutate(.[[1]] = .[[1]] + .[[2]])

gives:

Error: unexpected '=' in "iris %>% head %>% mutate(.[[1]] =".

However, the following works:

iris %>% head %>% mutate(sum = .[[1]] + .[[2]])
Community
  • 1
  • 1
pluke
  • 3,832
  • 5
  • 45
  • 68
  • 1
    Why do you want to do this in ways that are not supported. There is already standard ways to call the column with column names. If there are columns that start with number, change it to standard names as it will become difficult while you do this on other cases – akrun Mar 31 '17 at 10:04
  • I'm making a generic function to work on multiple tables with different column names, but the same data format. I could temporaily rename the columns make the mutate and give them back their old names, but this would be a neater solution. If this isn't supported, then that's the answer I was looking for – pluke Mar 31 '17 at 10:05
  • 2
    In that case, it would be better to use `base R` `iris[[1]] <- iris[[1]] + iris[[2]]` – akrun Mar 31 '17 at 10:06
  • 3
    Thanks, that solves it, I'm always confused why these questions get voted down though, there are often other ways at solving things in R. Was this a silly question? Should I remove it? – pluke Mar 31 '17 at 10:33
  • 1
    Possible duplicate of [sum two columns in R](https://stackoverflow.com/questions/26046776/sum-two-columns-in-r) – Ronak Shah Nov 27 '17 at 05:30
  • 1
    I don't think so, this is about dplyr and using a column index for the destination and source. – pluke Nov 27 '17 at 10:22
  • Have you found a `dplyr` solution to this problem – Julien Jul 26 '22 at 11:37
  • Afraid not, would be interested if someone else has though! – pluke Jul 26 '22 at 20:51

1 Answers1

2

We can do this in base R

iris[[1]] <- iris[[1]] + iris[[2]]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Can this be used to select, for example the second to last column? `iris %>% head %>% mutate(sum = .[[1]] + .[[-2]])` does not work – Phillip Black Nov 17 '19 at 14:19
  • @PhillipBlack Did you meant `iris %>% head %>% mutate(sum = rowSums(.[2:(ncol(.)-1)]))` – akrun Nov 17 '19 at 18:45
  • exactly! for on lookers: .[[(ncol(.)-1)]] and [(ncol(.)-1)] will call either a vector of the column or the column itself. – PDog Nov 18 '19 at 21:17
  • @akrun, I'm with the same issue `aeps_1_fine %>% mutate(.[[1]] = as.numeric(.[[1]]))` . Any way to do this one with mutate? – Luis Mar 04 '21 at 20:22
  • 4
    @Luis you can use `aeps_1_fine %>% mutate(!! names(.)[1] := as.numeric(!! rlang::sym(names(.)[1])))` or use across i.e. `aeps_1_fine %>% mutate(across(1, as.numeric))` – akrun Mar 04 '21 at 20:25
  • 2
    I don't know how you know so much about R and R programming!! Thanks much! It worked! – Luis Mar 04 '21 at 20:42