Inserts a new row or column into a data.frame at a specified location
insert(x, MARGIN = 1, value = NULL, idx, name = NULL)
x | Existing data.frame |
---|---|
MARGIN | Insert a 1 = row or 2 = column |
value | A vector of values equal to the length of MARGIN, if nothing specified values with be NA |
idx | Index position to insert row or column |
name | Name of new column (not used for rows, MARGIN=1) |
A data.frame with the new row or column inserted
Where there are methods to easily add a row/column to the end or beginning of a data.frame, it is not straight forward to insert data at a specific location within the data.frame. This function allows for inserting a vector at a specific location eg., between columns or rows 1 and 2 where row/column 2 is moved to the 3rd position and a new vector of values is inserted into the 2nd position.
Jeffrey S. Evans <jeffrey_evans@tnc.org>
#> Inserting row#> ID y #> 1 1 0.27993559 #> 2 NA NA #> 3 2 0.78022466 #> 4 3 0.34410797 #> 5 4 0.08978361 #> 6 5 0.79301521 #> 7 6 0.85302540 #> 8 7 0.42590664 #> 9 8 0.78807564 #> 10 9 0.47899806 #> 11 10 0.59109823#> Inserting row#> ID y #> 1 1 0.27993559 #> 2 20 0.00000000 #> 3 2 0.78022466 #> 4 3 0.34410797 #> 5 4 0.08978361 #> 6 5 0.79301521 #> 7 6 0.85302540 #> 8 7 0.42590664 #> 9 8 0.78807564 #> 10 9 0.47899806 #> 11 10 0.59109823# insert column insert(d, MARGIN=2, idx=2)#> Inserting column#> ID V1 y #> 1 1 NA 0.27993559 #> 2 2 NA 0.78022466 #> 3 3 NA 0.34410797 #> 4 4 NA 0.08978361 #> 5 5 NA 0.79301521 #> 6 6 NA 0.85302540 #> 7 7 NA 0.42590664 #> 8 8 NA 0.78807564 #> 9 9 NA 0.47899806 #> 10 10 NA 0.59109823#> Inserting column#> ID x y #> 1 1 0 0.27993559 #> 2 2 0 0.78022466 #> 3 3 0 0.34410797 #> 4 4 0 0.08978361 #> 5 5 0 0.79301521 #> 6 6 0 0.85302540 #> 7 7 0 0.42590664 #> 8 8 0 0.78807564 #> 9 9 0 0.47899806 #> 10 10 0 0.59109823