I have this sample data:
cvar <- c("2015-11-01","2015-11-02","All") nvar1 <- c(12,10,5) nvar2 <- c(7,5,6) data <- cbind.data.frame(cvar,nvar1,nvar2)
And I just want to add a new row to the data.frame containing the sums of nvar1 & nvar2 and a character, so with base R I would just use
data[nrow(data)+1,] <- c("add",sum(data[,2]),sum(data[,3]))
or something more clever with lapply, but just to show you what I'm looking for.
I would like this simple command within the pipe environment, so data %>% ... gives me the above outcome.
Appreciate any help, thank you.
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.
Use tibble_row() to ensure that the new data has only one row. add_case() is an alias of add_row() .
You can add rows to the pandas dataframe using df. iLOC[i] = ['col-1-value', 'col-2-value', ' col-3-value '] statement. Other options available to add rows to the dataframe are, append()
To add or insert observation/row to an existing Data Frame in R, we use rbind() function. We can add single or multiple observations/rows to a Data Frame in R using rbind() function.
With tibble
version 1.2 you can use add_row()
https://blog.rstudio.org/2016/08/29/tibble-1-2-0/
data %>% add_row(cvar = "add", nvar1 = sum(nvar1), nvar2 = sum(nvar2))
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