31

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.

5
  • You have any data.table here.
    – user3710546
    Nov 6, 2015 at 11:38
  • as soon as you give it into the pipe it will become a data.table, doesnt it?
    – Sebastian
    Nov 6, 2015 at 11:38
  • data.table is a different package. TO convert to data.table, it should be data.table(cvar, ....) If you are using dplyr, then try with bindrows
    – akrun
    Nov 6, 2015 at 11:39
  • You may be referring to tbl_df
    – Pierre L
    Nov 6, 2015 at 11:39
  • Ah okay, I'm sorry will edit this.
    – Sebastian
    Nov 6, 2015 at 11:40

5 Answers 5

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

43

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))
2
  • 9
    this is working because the vectors are defined in the global environment. Would be nice to have a lazy eval of the column names. Opened an issue
    – aurelien
    Dec 1, 2016 at 10:37
  • 1
    This is now working fine with lazy eval of column names, clearly the most tidyverse option imo! Dec 11, 2017 at 15:41
19

Something like this then maybe:

data %>% 
     rbind(c("add",sum(nvar1),sum(nvar2)))
#        cvar nvar1 nvar2
#1 2015-11-01    12     7
#2 2015-11-02    10     5
#3        All     5     6
#4        add    27    18

Edit:

According to your comment, this will work:

data %>% 
  mutate(nvar3 = nvar1) %>% 
  rbind(c("add",sum(nvar1),sum(nvar2),sum(.$nvar3))) 

Using the . will allow rbind to find nvar3

Edit2:

Provide the new row as a list and it will maintain the column classes:

> str(
+ data %>% 
+   mutate(nvar3 = nvar1) %>% 
+   rbind(list("add",sum(nvar1),sum(nvar2),sum(.$nvar3))) 
+ )
'data.frame':   4 obs. of  4 variables:
 $ cvar : chr  "2015-11-01" "2015-11-02" "All" "add"
 $ nvar1: num  12 10 5 27
 $ nvar2: num  7 5 6 18
 $ nvar3: num  12 10 5 27
7
  • The only way I can justify "dplyr" here is if you include the conversion of the first column to "character". data %>% mutate(cvar = as.character(cvar)) %>% rbind(c("add",sum(nvar1),sum(nvar2))). Otherwise, rbind(data, c("add",sum(nvar1),sum(nvar2))) would also do the same.... Nov 6, 2015 at 11:57
  • Thank you LyzandeR, that does solve the problem stated above, +1. But inside a pipe it doesn't work for me say: data %>% mutate(nvar3 = nvar1) %>% rbind(c("add",sum(nvar1),sum(nvar2),sum(nvar3))) , I need to use the rbind after a long series of transformations, did not mention this in the question sorry for that..
    – Sebastian
    Nov 6, 2015 at 11:58
  • @Sebastian Yeah in the case you describe above nvar3 cannot be found in data and hence the error. You should do it like this: data %>% mutate(nvar3 = nvar1) %>% rbind(c("add",sum(nvar1),sum(nvar2),sum(.$nvar3))) and it will work.
    – LyzandeR
    Nov 6, 2015 at 12:01
  • @AnandaMahto I totally agree. It seems that the OP needed it as a step in a more complex situation.
    – LyzandeR
    Nov 6, 2015 at 12:04
  • By rbinding a character vector, you've converted the nvars to char in the result.
    – Frank
    Nov 6, 2015 at 14:15
13

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
4
  • 3
    Use bind_rows(data, .) to add to the end.
    – krlmlr
    Dec 1, 2016 at 12:52
  • 1
    @krlmlr Thanks! I didn't realize it's that easy to add the new row at the end. Funily the warning message In bind_rows_(x, .id) : binding factor and character vector, coercing into character vector appears while doing this – but it doesn't appear the other way round (bind_rows(., data)). Do you know why that is?
    – Salim B
    Dec 5, 2016 at 13:57
  • Simpler example: bind_rows(data_frame(a = "a"), data_frame(a = factor("a"))) vs. bind_rows(data_frame(a = factor("a")), data_frame(a = "a")) . Seems to depend on the order, perhaps the absence of a warning in my first example is a simple omission. Double-check the dplyr NEWS to be sure.
    – krlmlr
    Dec 5, 2016 at 14:17
  • 2
    Yeah, I've noticed that it depends on the order... but to me this behaviour seems inconsistent so I've opened a corresponding issue on GitHub :)
    – Salim B
    Dec 13, 2016 at 14:21
6

One option utilizing summarise_all() and bind_rows() could be:

data %>% 
 bind_rows(summarise_all(., ~ if (is.numeric(.)) sum(.) else "add"))

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

Or adding the row and then calculating the sum only for that last row using if_else():

data %>%
 add_row(cvar = "add") %>%
 mutate_at(-1, ~ if_else(row_number() == max(row_number()), sum(., na.rm = TRUE), .))

Or an alternative to @Rickard's answer when the variables are not in global environment:

data %>% 
 add_row(cvar = "add", nvar1 = sum(data$nvar1), nvar2 = sum(data$nvar2))
2
  • Top ! Thanks Would add to use sum(., na.rm = T)
    – SJGD
    Apr 23, 2020 at 3:02
  • 1
    Would also add to use brackets to prevent warnings in RStudio: data %>% bind_rows(summarise_all(., ~ if (is.numeric(.)) {sum(., na.rm = T)} else {"Total"}))
    – SJGD
    Apr 23, 2020 at 3:24
0

If someone is still looking for an universal solution I would be use:

cvar <- c("2015-11-01","2015-11-02","All")
nvar1 <- c(12,10,5)
nvar2 <- c(7,5,6)
data <- tibble::tibble(cvar,nvar1,nvar2)

purrr::map_df(data, ~c(.x, ifelse(is.numeric(.x), sum(.x, na.rm=TRUE), NA)))

P.S. I use tibble to keep character because a data frame converts them to factor and base::c "destroy" them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.