Coder_in_training
Coder_in_training

Reputation: 1

Create new columns using mutate and across beside existing columns in R

I have the following sample data where I am trying to the new columns to be directly beside the existing columns and not at the end of the data frame. I do not want to use sort as I need to keep the order.

library (dplyr)

df <- data.frame(data_in= 2:10,     #Data frame
data_ft= 3:11,
data_mile= 4:12)

df`
data_in data_ft data_mile
1       2       3         4
2       3       4         5
3       4       5         6
4       5       6         7
5       6       7         8
6       7       8         9
7       8       9        10
8       9      10        11
9      10      11        12
df_new<- df%>%
mutate(across(contains("in"),                      #Why this does not work?
~cbind(.x * 25.4),
.names = "{sub('in', 'mm', col)}")) # ETC

How can I let the new columns be directly beside the existing columns they came from and NOT at the end of the data frame? Also I do NOT want to use sort as I have many columns and need to maintain the order of the data frame.

I'm new to R so please bare with me.

I have tried using add_column as well.

I'm expecting the data frame to look like this:

data_in data_mm data_ft data_cm data_mile data_km

1 25.4 2 60.96 4 6.4

This gets the desired order:

df <- data.frame(data_in= 2:10,   #Data framedata_ft= 3:11,data_mile= 4:12)
df<- df %>%mutate(across(everything(), ~ cbind(., .*2))) #Works like this
df

But when I used contains() and names() in the first code above, the outcome is different.

Upvotes: 0

Views: 191

Answers (1)

Julian Selke
Julian Selke

Reputation: 298

You can specify the position by setting the .after argument in mutate. See documentation here: https://dplyr.tidyverse.org/reference/mutate.html

df_new <- df %>%
mutate(across(contains("in"), 
~ .x * 25.4, 
.names = "{sub('in', 'mm', col)}"), .after = 1)

This will produce the desired output:

> df_new
  data_in data_mm data_ft data_mile
1       2    50.8       3         4
2       3    76.2       4         5
3       4   101.6       5         6
4       5   127.0       6         7
5       6   152.4       7         8
6       7   177.8       8         9
7       8   203.2       9        10
8       9   228.6      10        11
9      10   254.0      11        12

Upvotes: 2

Related Questions