'How do I get the column name in a for loop? [duplicate]
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
Solution 1:[1]
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"))
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | liiiiiin |
