Adding the vlue of columns in a tibble

I have Data tibble as below.

For every Year, i want to add New column Total which adds values from Sep:Aug.

I am using as below:

Data%>%mutate(TOTAL= sum(Sep:Aug))

But it is not giving correct values. Also original data can have some NA values as well in data.

YEAR Sep Oct Nov Dec Jan Feb Mar Apr May Jun Jul Aug

1 2009 64. 545. 67. 71. 746. 590. 775. 752. 823. 753. 81. 800.
2 2010 8183. 783. 759. 8682. 51. 687. 8115. 743. 885. 708. 669. 780.
3 2011 637. 761. 996. 87. 783. 75. 830. 756. 860. 862. 889. 7419.
4 2012 795. 875. 976. 536. 898. 691. 885. 779. 724. 739. 796. 736.

Most dplyr and R functionality is for columns/vectors, so to apply a function across columns requires referencing the columns individually or an apply or rowwise function call. I find rowwise a little abstract so I like to do it this way.

On the iris data set

library(tidyverse)
iris %>% mutate(Total = across(Sepal.Length:Petal.Width) %>% apply(1, sum))

On your data set
Data %>% mutate(TOTAL = across(Sep:Aug) %>% apply(1, sum))

dat <- data.frame(
  YEAR =
    c(2009, 2010, 2011, 2012),
  Sep =
    c(64, 8183, 637, 795),
  Oct =
    c(545, 783, 761, 875),
  Nov =
    c(67, 759, 996, 976),
  Dec =
    c(71, 8682, 87, 536),
  Jan =
    c(NA, 51, 783, 898),
  Feb =
    c(590, 687, 75, 691),
  Mar =
    c(775, 8115, 830, 885),
  Apr =
    c(752, 743, 756, 779),
  May =
    c(823, 885, 860, 724),
  Jun =
    c(753, 708, 862, 739),
  Jul =
    c(81, 669, 889, 796),
  Aug =
    c(800, 780, 7419, 736))

dat["Total"] <- rowSums(dat[,2:13],na.rm = TRUE)
dat
#>   YEAR  Sep Oct Nov  Dec Jan Feb  Mar Apr May Jun Jul  Aug Total
#> 1 2009   64 545  67   71  NA 590  775 752 823 753  81  800  5321
#> 2 2010 8183 783 759 8682  51 687 8115 743 885 708 669  780 31045
#> 3 2011  637 761 996   87 783  75  830 756 860 862 889 7419 14955
#> 4 2012  795 875 976  536 898 691  885 779 724 739 796  736  9430

Thanks. Can you pls adivse if i wnat to add 2 rows below in this data as such:
Sep Oct Nov Dec Jan
Avergae_2 Yr
Avergae 4 yr

Avg_2 Yr Sep shud have avergae of last 2 years of Sep values . Similary Avg_4Yr shud have avergae of last 4 years.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.