0

How to find sum of a specific part of a table. I know for a full column, i can just use sum(X[, 'expenditure']), but I want to sum expenditures for only January month. I am using imported data from a csv file. I am encouraged to use sum or colSums.

The data is too big to show, but you can visualise it. Here is a sample:

Month   Expenditure
Jan.    20
Jan.    28
March.  50
March.  54
July.   07
Shazyam
  • 1
  • 1
  • 1
    Subset your data.frame to contain the rows you want to sum. `sum(subset(X, Month=="Jan.")[, "Expenditure"])` – MrFlick Oct 06 '20 at 06:16

1 Answers1

1

You can subset in the square braces by comparing a vector of the month variable, df$Month, to the character string Jan. and returning the expenditure variable where there is a match.

df[df$Month == "Jan.", "Expenditure"]

Additionally, the syntax becomes shorter and you can do this for all months in a single expression if you use a data.table

library(data.table)
setDT(df)
# Just January 
df[Month == "Jan.", sum(Expenditure)]
# Each month 
df[, sum(Expenditure), by = Month]
rg255
  • 4,119
  • 3
  • 22
  • 40