This function inserts one or more columns or rows before or after another column or row in a data frame or matrix. It is similar to cbind except that the inserted column(s)/row(s) can be placed anywhere.
Arguments
- x
Data frame, matrix, or vector with same number of columns or rows or elements as
into.- into
Data frame or matrix into which
xis to be inserted.- at
Character, integer, or
NULL. Name of column or column number or name of row or row number at which to do insertion. IfNULL(default), the result is exactly the same ascbind(into, xexcept that it retains row numbers or column names frominto.- before
Logical, if
TRUE(default) then the insertion will occur in front of the column or row named inat, ifFALSEthen after. Ignored ifatisNULL.
Examples
x <- data.frame(y1=11:15, y2=rev(letters)[1:5])
into <- data.frame(x1=1:5, x2='valid', x3=letters[1:5], x4=LETTERS[1:5], x5='stuff')
insertCol(x, into=into, at='x3')
#> x1 x2 y1 y2 x3 x4 x5
#> 1 1 valid 11 z a A stuff
#> 2 2 valid 12 y b B stuff
#> 3 3 valid 13 x c C stuff
#> 4 4 valid 14 w d D stuff
#> 5 5 valid 15 v e E stuff
insertCol(x, into=into, at='x3', before=FALSE)
#> x1 x2 x3 y1 y2 x4 x5
#> 1 1 valid a 11 z A stuff
#> 2 2 valid b 12 y B stuff
#> 3 3 valid c 13 x C stuff
#> 4 4 valid d 14 w D stuff
#> 5 5 valid e 15 v E stuff
insertCol(x, into)
#> x1 x2 x3 x4 x5 y1 y2
#> 1 1 valid a A stuff 11 z
#> 2 2 valid b B stuff 12 y
#> 3 3 valid c C stuff 13 x
#> 4 4 valid d D stuff 14 w
#> 5 5 valid e E stuff 15 v
x <- data.frame(x1=1:3, x2=LETTERS[1:3])
into <- data.frame(x1=11:15, x2='valid')
row.names(into) <- letters[1:5]
insertRow(x, into=into, at='b')
#> x1 x2
#> a 11 valid
#> 1 1 A
#> 2 2 B
#> 3 3 C
#> b 12 valid
#> c 13 valid
#> d 14 valid
#> e 15 valid
insertRow(x, into=into, at='b', before=FALSE)
#> x1 x2
#> a 11 valid
#> b 12 valid
#> 1 1 A
#> 2 2 B
#> 3 3 C
#> c 13 valid
#> d 14 valid
#> e 15 valid
insertRow(x, into)
#> x1 x2
#> a 11 valid
#> b 12 valid
#> c 13 valid
#> d 14 valid
#> e 15 valid
#> 1 1 A
#> 2 2 B
#> 3 3 C
