Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dplyr mutate new column at a specified location

Tags:

r

dplyr

tidyverse

An example:

a = c(10,20,30)
b = c(1,2,3)
c = c(4,5,6)
d = c(7,8,9)
df=data.frame(a,b,c,d)

library(dplyr)

df_1 = df %>% mutate(a1=sum(a+1))

How do I add "a1" after "a" (or any other defined position) and NOT at the end?

Thank you.

like image 937
ip2018 Avatar asked Jul 03 '18 19:07

ip2018


People also ask

Does mutate create a new column in R?

mutate() creates new columns that are functions of existing variables. It can also modify (if the name is the same as an existing column) and delete columns (by setting their value to NULL ).

How does dplyr mutate work?

mutate() adds new variables and preserves existing ones; transmute() adds new variables and drops existing ones. New variables overwrite existing variables of the same name. Variables can be removed by setting their value to NULL .

How do you add a new column in R?

1 Adding new columns. You can add new columns to a dataframe using the $ and assignment <- operators. To do this, just use the df$name notation and assign a new vector of data to it. As you can see, survey has a new column with the name sex with the values we specified earlier.


1 Answers

An update that might be useful for others who find this question - this can now be achieved directly within mutate (I'm using dplyr v1.0.2).

Just specify which existing column the new column should be positioned after or before, e.g.:

df_after <- df %>% 
   mutate(a1=sum(a+1), .after = a)

df_before <- df %>% 
   mutate(a1=sum(a+1), .before = b)
like image 126
monkeytennis Avatar answered Oct 01 '22 03:10

monkeytennis