Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R dplyr mutate on column index

Tags:

r

dplyr

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]])
like image 537
16 revs, 12 users 31% Avatar asked Oct 29 '22 09:10

16 revs, 12 users 31%


1 Answers

We can do this in base R

iris[[1]] <- iris[[1]] + iris[[2]]
like image 168
akrun Avatar answered Nov 15 '22 05:11

akrun