Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using R to find max value for loop

Tags:

r

Here is my problem, I have a a series of variables that get matched to a date and multiple days time. I would like to walk through my entire list and first find the max value for each day and then print that along with the corresponding time and date. Heres what i have so far.

for (i in 1:numDays)  
{

   temp <- which(test[[i]]$Date == numDays[i])
   temp <- test[[i]][temp,]
   High[rowCnt, (i-2)+2] <- max(temp$High)
   rowCnt <- rowCnt + 1 
}

any suggestions?

thanks For example:

Day Time Valeue 
x    5    0
x    6    1 
x    7    2
x    8    3
y    1    12
y    2    0
y    3    1
y    4    5

so this should return:

day time value
x   8    3
y   1    12
like image 426
Junior R Avatar asked Feb 13 '26 05:02

Junior R


2 Answers

Using by for example:

do.call(rbind,by(test,test$Day,
           function(x) x[which.max(x$Value),]))

  Day Time Value
x   x    8     3
y   y    1    12
like image 187
agstudy Avatar answered Feb 15 '26 19:02

agstudy


temp[ with( temp, ave(Valeue, Day, FUN=max) ) == temp$Valeue , ] 
#--------------
  Day Time Valeue
4   x    8      3
5   y    1     12

This is a example of making a logical vector that spans the number of the rows of the dataframe being selected.

like image 36
IRTFM Avatar answered Feb 15 '26 17:02

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!