Insert one or more new columns into a data frame before or after the given column
Usage
insertColumns(
Data,
...,
before = "",
after = "",
stringsAsFactors = defaultIfNULL(options()$stringsAsFactors, FALSE)
)
Arguments
- Data
data frame
- ...
named objects each of which will be a new column in the data frame. Each object must have as many elements as Data has rows.
- before
name of column before which to insert the new column(s)
- after
name of column after which to insert the new column(s)
- stringsAsFactors
passed on to data.frame() and cbind()
Value
data frame Data
with new columns inserted before the column
named as given in before
or after the column named as given in
after
Examples
Data <- data.frame(A = 1:5, B = 2:6)
# Insert new columns X and Y before column "B"
insertColumns(Data, before = "B", X = paste0("x", 1:5), Y = paste0("y", 1:5))
#> A X Y B
#> 1 1 x1 y1 2
#> 2 2 x2 y2 3
#> 3 3 x3 y3 4
#> 4 4 x4 y4 5
#> 5 5 x5 y5 6
# This is the same as inserting new columns X and Y after column "A":
insertColumns(Data, after = "A", X = paste0("x", 1:5), Y = paste0("y", 1:5))
#> A X Y B
#> 1 1 x1 y1 2
#> 2 2 x2 y2 3
#> 3 3 x3 y3 4
#> 4 4 x4 y4 5
#> 5 5 x5 y5 6
# You may also insert before the first...
insertColumns(Data, before = "A", X = paste0("x", 1:5), Y = paste0("y", 1:5))
#> X Y A B
#> 1 x1 y1 1 2
#> 2 x2 y2 2 3
#> 3 x3 y3 3 4
#> 4 x4 y4 4 5
#> 5 x5 y5 5 6
# ... or after the last column
insertColumns(Data, after = "B", X = paste0("x", 1:5), Y = paste0("y", 1:5))
#> A B X Y
#> 1 1 2 x1 y1
#> 2 2 3 x2 y2
#> 3 3 4 x3 y3
#> 4 4 5 x4 y4
#> 5 5 6 x5 y5