1
data <- c(491, 301, 573, 412, 947, 102, 840, 203, 930)
sales <- matrix(data, ncol = 3, byrow = TRUE)
colnames(sales) = c("week 1", "week 2", "week 3")
rownames(sales) = c("store 1", "store 2", "store 3")
sales
maximum = c()

for(i in 1:nrow(sales)) {
      maximum[i] = max(sales[i,])
            cat(paste("The maximum number of sales of", 
            rownames(sales)[i], "is", maximum[i], "\n"))
    }

**Basically, my table will look like this, below** 
             | week 1 | week 2 |  week 3  |
     store 1 |  491   |  301   |   573    |
     store 2 |  412   |  937   |   102    |
     store 3 |  840   |  203   |   930    |
    The maximum number of sales of store 1 is 573 
    The maximum number of sales of store 2 is 937 
    The maximum number of sales of store 3 is 830

                                   

My question is how do I add the week number (column name) to my for-loop? I want an output that looks like this:

The maximum number of sales of store 1 is 573, which was on week 3
The maximum number of sales of store 2 is 937, which was on week 2
The maximum number of sales of store 3 is 830, which was on week 1
                     
MrFlick
  • 195,160
  • 17
  • 277
  • 295

1 Answers1

0

This could be a possible solution?

for(i in 1:nrow(sales)) {
  
  maximum[i] = max(sales[i,])
  
  week = names(which(sales[i,] == maximum[i]))
  
  cat(paste("The maximum number of sales of", 
            rownames(sales)[i], 
            "is", 
            maximum[i], 
            ", which was on ",
            week,
            "\n"))
}
liiiiiin
  • 119
  • 4