0

I need to calculate : a) the maximum and minimum (temperature) values for every row of my data set(200 such rows). b) Every column corresponds to 'Jan', 'Feb' ... 'Dec' (12 columns). Thus, I need to find the month associated with maximum and minimum temperature.

For (a) this works:

 i= 1
  temp.max = NULL
  for(i in 1:200)
  { temp.max[i]<- max(temp.data[i,1:12])}

Can someone please help me with (b)?

eg. If the dataset looks like :

Jan Feb Mar Apr May Jun ... Dec
1     2   3   4  12   6       2

Max Value is 12. I need to output that, 'May' is the corresponding month.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453

2 Answers2

3

max.col is handy for this (I've just repeated your first row 3 times to show it works for multiple rows):

names(dat)[max.col(dat,ties.method="first")]
#[1] "May" "May" "May"

data used:

dat <- setNames(data.frame(matrix(c(1,2,3,4,12,6,2),nrow=1)),month.abb[1:7])
dat <- dat[rep(1,3),]
thelatemail
  • 91,185
  • 12
  • 128
  • 188
0
maxvals <- apply(mydata,1,max)
maxlocs <- colnames(mydata)[apply(mydata,1,which.max)]

and similarly for min/which.min

By the way, your solution to (a) puts you in the second circle of Patrick Burns's R Inferno; the inefficiency probably won't matter in this application but could come back to bite you later ...

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Hi! The code is working. However, I am not able to iterate across the 200 rows I have. This is the code : i= 1 temp.max = NULL for(i in 1:200) {maxvals <- apply(litter[i,1:12],1,max) maxlocs <- colnames(litter[i,1:12])[apply(litter[i,1:12],1,which.max)] } –  Apr 15 '15 at 01:01
  • you don't need to do it 200 times! Just `L <- litter[,1:12]; apply(L,1,max)` and `colnames(L)[apply(L,1,which.max)]` -- or use @thelatemail's slightly more efficient answer. – Ben Bolker Apr 15 '15 at 01:07
  • Hi! I am running into an error which says : "invalid subscript type 'list'. Can you please help me? –  Jul 15 '15 at 02:17