Reputation: 35
I have a dataframe for which has sale value for each zone for first three quarters of the year and its total
Zone Q1 Q2 Q3 total
a 15.21 53.31 80.1 109.04
b 19.2 52.35 71.5 84.1
c 10.24 28.56 70.41 100.05
d 11.94 38.58 59.72 76.34
e 11.05 37.32 53.34 67.97
I have to find the maximum sales value for each quarters along with the zone name. I used sapply(df[,c(2:5)],function(X) max(X))
got the maximum sales value for each quarter as well the total. which resulted in
Q1 Q2 Q3 Total
19.2 53.51 80.10 109.04
But it also requires the zone name for each maximum value. which function can be used to get the zone names or only way is to find each of the zone ,append it to a vector?
Upvotes: 0
Views: 165
Reputation: 18425
You could do something like this...
df2 <- df[,-1]
#difference columns to get quarterly sales (yours appear to be cumulative)
df2[,-1] <- df2[,-1]-df2[,-4]
#rename final quarter
names(df2)[4] <- "Q4"
#create data frame with best sales for each quarter
best <- data.frame(Zone=df$Zone[apply(df2, 2, which.max)],
Sales=apply(df2, 2, max))
best
Zone Sales
Q1 b 19.20
Q2 a 38.10
Q3 c 41.85
Q4 c 29.64
Upvotes: 0
Reputation: 1432
No it can be done like this. You can make the function accordingly.
sapply(df[,c(2:4)],function(X) df$Zone[which.max(X)])
Appreciate if this works.
Upvotes: 3