3
votes

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
4
some data to work with and showing your desired output would be nice.Arun

4 Answers

2
votes
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.

1
votes

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
0
votes

And just for fun:

merge(dat, aggregate(Valeue ~ Day, dat, max) )

#  Day Valeue Time
#1   x      3    8
#2   y     12    1

And if you have missing values (same logic applies to the FUN= part of @Dwin's answer)

merge(dat, aggregate(Valeue ~ Day, dat, max, na.rm=TRUE) )
0
votes

Yet another way:

# Dummy Data
dat <- data.frame(
    day=sample(c("x","y"),10,replace=TRUE),
    time=sample(1:10),
    value=sample(1:10))

# Find location of maxima in each column, subset by locations
dat[sapply(dat[2:3],which.max),]