Can I insert a vector
as a row in a data.frame
? If so how?
To add row to R Data Frame, append the list or vector representing the row, to the end of the data frame. nrow(df) returns the number of rows in data frame. nrow(df) + 1 means the next row after the end of data frame. Assign the new row to this row position in the data frame.
You can quickly append one or more rows to a data frame in R by using one of the following methods: Method 1: Use rbind() to append data frames. Method 2: Use nrow() to append a row.
Data Frames in R Language are generic data objects of R which are used to store the tabular data. Data frames can also be interpreted as matrices where each column of a matrix can be of the different data types. DataFrame is made up of three principal components, the data, rows, and columns.
I wouldn't claim this to be the most elegant and pretty solution out there, but it gets the job done. Notice that each dataframe row carries its own row name, which becomes a problem when inserting new lines. That being said, you can mend this with row.names
(see below).
my.df <- data.frame(a = runif(10), b = runif(10), c = runif(10)) my.vec <- c(1, 1, 1) new.df <- rbind(my.df[1:5, ], my.vec, my.df[6:nrow(my.df), ]) new.df a b c 1 0.45433791 0.3798105 0.84514864 2 0.07074529 0.4985765 0.53912585 3 0.09645574 0.5441647 0.96636213 4 0.60788436 0.6070706 0.53791603 5 0.01593911 0.1697248 0.62697924 6 1.00000000 1.0000000 1.00000000 61 0.98455694 0.2206702 0.85500531 7 0.85356834 0.5279596 0.27462326 8 0.48028935 0.6689572 0.05428349 9 0.95675901 0.6875491 0.77642924 10 0.24691330 0.7980741 0.24013096 row.names(new.df) <- 1:nrow(new.df) # make row names pretty again
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With