Add row to data frame with dplyr

后端 未结 5 1289
隐瞒了意图╮
隐瞒了意图╮ 2021-02-03 23:15

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,n         


        
5条回答
  •  天涯浪人
    2021-02-03 23:50

    Using only dplyr you could do the following

    data %<>%
      summarise(cvar = "add",
                nvar1 = sum(nvar1),
                nvar2 = sum(nvar2)) %>%
      bind_rows(data)
    

    which results in

            cvar nvar1 nvar2
    1        add    27    18
    2 2015-11-01    12     7
    3 2015-11-02    10     5
    4        All     5     6
    

    Note that this way the new row is added at the beginning rather than the end of the original dataframe.

    If you want to add the new row at the end instead, use the following code (thanks to krlmlr for pointing this out)

    data %<>%
      summarise(cvar = "add",
                nvar1 = sum(nvar1),
                nvar2 = sum(nvar2)) %>%
      bind_rows(data, .)
    

    which results in

            cvar nvar1 nvar2
    1 2015-11-01    12     7
    2 2015-11-02    10     5
    3        All     5     6
    4        add    27    18
    

提交回复
热议问题