Building on prior answers, new rows can be added to a data frame using replacement functions. Replacement functions can encapsulate code complexity, which is advantageous when row additions are occurring multiple times in the same code.
Multiple versions of such a function are presented in order of increasing complexity.
Version 1: This version is like the answers by @MatheusAraujo or @YtsendeBoer. It is compact and useful if all column data for the new row is present in a fixed order.
'new_row<-'<- function(x, value){x[nrow(x) + 1,] <- value; x}
df <- data.frame(A = 1, B = 2, C = 3)
new_row(df) <- c(4, 5, 6)
new_row(df) <- list(7, 8, 9)
Version 2: Though slightly longer, this version improves traceability by keying new data to the column name. All named columns must be present, though not necessarily in order, when adding a new row.
'new_row<-'<- function(x, value){
x[nrow(x) + 1,] <- sapply(names(x), function(y){value[y]}); x
}
df <- data.frame(A = 1, B = 2, C = 3)
new_row(df) <- c(B = 1, C = 2, A = 3)
new_row(df) <- list(C = 1, A = 2, B = 3)
new_row(df) <- data.frame(A = 3, B = 4, C = 5)
Version 3: This bulkier version will work when columns are missing and when new named columns are included. This is advantageous when new rows need adding while column data is still incomplete or when new rows only partially fit the data frame.
'new_row<-'<- function(x, value){
x[names(value)[!is.element(names(value), names(x))]] <- numeric()
x[nrow(x) + 1,] <- sapply(names(x), function(y){
if(is.element(y,names(value))){return(value[y])}else{return(NA)}
}); x}
df <- data.frame(A = 1, B = 2, C = 3)
new_row(df) <- NA
new_row(df) <- c(A = 5)
new_row(df) <- list(C = 1, A = 2, B = 1)
new_row(df) <- data.frame(Z = 1000)