1

Let's say I have a dataframe with columns a,b,c,d,e,f,g,h.

I want to add up the values of column d and e and create a column containing the results right after d and e such that it becomes:

a,b,c,d,e,newcolumn,f,g,h

Is there any way to do this? As I have found it very frustrating to reorder columns in R, especially when you have a huge dataframe with many columns.

Any help is appreciated!

TYL
  • 1,577
  • 20
  • 33

1 Answers1

4

With dplyr

library(dplyr)

data %>%
 mutate(newcolumn = d + e) %>%
 select(a,b,c,d,e,newcolumn,f,g,h)

with data.table

setDT(data)

data[,newcolumn := d + e,] 
setcolorder(data, c("a","b","c","d","e","newcolumn")

with tibble

library(tibble)

add_column(data, "newcolumn" = data$d + data$e, .after = "e")

with base

data <- within(data, newcolumn <- d + e)
data <- data[, c(1:5, 9, 6:8)]

Humpelstielzchen
  • 6,126
  • 3
  • 14
  • 34