-1

I need a for loop to sum the values in a DataFrame column in r. The code below gives me the sum of the value when the date column == '2014-01-01'. I also need when date == '2014-01-02' to '2014-31-12'

# sum of the half an hour data into daily total.
day1 <- subset(df, DATE =='2014-01-01',select= FridgeRange)
sum(day1)

Please if you can also add the result to a dataframe that will be awesome.

mhovd
  • 3,724
  • 2
  • 21
  • 47
  • So you want to sum `FridgeRange` values for each day? Do you want `result <- aggregate(FridgeRange~DATE, df, sum, na.rm = TRUE)` Or `result <- ave(df$FridgeRange, df$DATE, FUN = function(x) sum(x, na.rm = TRUE))` – Ronak Shah Dec 02 '20 at 03:36
  • Thank you Ronak ShahI want the aggregate not average. I have the Date and FridgeRange Column. I just want to sum FridgeRange values for each day. – chidom george Dec 02 '20 at 03:53
  • Did you run the code which I shared with you? It is not taking average, it is just taking the `sum`. – Ronak Shah Dec 02 '20 at 03:54
  • I just ran the code. The first Code worked. Thanks Ronak. – chidom george Dec 02 '20 at 04:00

2 Answers2

0

library(dplyr)

dat = read.csv("Your_file")

dateinbw = c("2014-01-01", "2014-01-02")

new_dat = filter(dat, DATE %in% dateinbw)

sum(new_dat$your_column)

0

This loop will cycle through the dates from 2014-01-01 to 2014-12-31. It's not exactly clear to me how you want to name the extracted variable and where to put it, so I will leave it to you.

date <- as.Date("2014-01-01") 

for (i in 1:364) {
     date <- date+1
     print(toString(date))
     x <- sum(subset(df, DATE==toString(date), select= FridgeRange))
     # now do something with x
     }
Mario Niepel
  • 1,095
  • 4
  • 19