Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add row to data frame with dplyr

Tags:

r

dplyr

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.

like image 745
Sebastian Avatar asked Nov 06 '15 11:11

Sebastian


People also ask

How do I add a row to an existing Dataframe in R?

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.

How do you add rows in Tibble R?

Use tibble_row() to ensure that the new data has only one row. add_case() is an alias of add_row() .

How do I add a row to a Dataframe?

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()

How do you add a new row in R studio?

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.


1 Answers

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)) 
like image 200
Rickard Avatar answered Sep 20 '22 12:09

Rickard