mercredi 9 novembre 2016

For loop compilation error in R

I have a data frame in R that lists monthly sales data by department for a store. Each record contains a month/year, a department name, and the total sales in that department for the month. I'm trying to calculate the mean sales by department, adding them to the vector avgs but I seem to be having two problems: the total sales per department is not compiling at all (its evaluating to zero) and avgs is compiling by record instead of by department. Here's what I have:

avgs = c()
for(dept in data$departmentName){
  total <- 0
  for(record in data){
    if(identical(data$departmentName, dept)){
      total <- total + data$ownerSales[record]
    }
  }
  avgs <- c(avgs, total/72)
}

Upon looking at avgs on completion of the loop, I find that it's returning a vector of zeroes the length of the data frame rather than a vector of 22 averages (there are 22 departments). I've been tweaking this forever and I'm sure it's a stupid mistake, but I can't figure out what it is. Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire