[R] Getting minimum value of a column according a factor column of a dataframe

Jim Lemon drj|m|emon @end|ng |rom gm@||@com
Thu Aug 25 23:42:45 CEST 2022


Hi Javad,
In that case, just modify the function to extract the rows with both
the minimum and maximum Q from each station

df1<-read.table(text="Code Y  M  D  Q  N  O
 41003 81 1 19 0.16 7.17 2.5
 41003 77 9 22 0.197 6.8 2.2
 41003 79 7 28 0.21 4.7 6.2
 41005 79 8 17 0.21 5.5 7.2
 41005 80 10 30 0.21 6.84 2.6
 41005 80 12 20 0.21 6.84 2.4
 41005 79 6 14 0.217 5.61 3.55
 41009 79 2 21 0.218 5.56 4.04
 41009 79 5 27 0.218 6.4 3.12
 41009 80 11 29 0.22 6.84 2.8
 41009 78 5 28 0.232 6 3.2
 41009 81 8 20 0.233 6.39 1.6
 41009 79 9 30 0.24 5.6 7.5
 41017 79 10 20 0.24 5.3 7.1
 41017 80 7 30 0.24 6.73 2.6",
 stringsAsFactors=FALSE,header=TRUE)

# define a function that returns the desired rows
minmaxQrow<-function(x) return(x[c(which.min(x$Q),which.max(x$Q)),])
# apply the function to the data frame
df1a<-by(df1,df1$Code,minmaxQrow)
# set the result to the first element of the list
df1b<-df1a[[1]]
# rbind the remaining rows
for(i in 2:length(df1a)) df1b<-rbind(df1b,df1a[[i]])
# display the result
df1b

Jim

On Fri, Aug 26, 2022 at 5:25 AM javad bayat <j.bayat194 using gmail.com> wrote:
> ...
> I think I should explain more about my request. I had a large data frame
> (11059 rows and 16 columns). The Code column represented the stations code,
> totally the number of stations were 128. At each station I had many
> measured variables, like Q and N and O, and these variables were measured
> in different years and days. The days that data were measured were
> different for each station, and due to this reason I had different rows for
> stations. For example, station number one (41009) had 158 rows and station
> number 2 (41011) had 113 rows. Note that the station's codes are not in
> order format (e.g smallest to largest).
> Back to my request, I wanted to extract the minimum value of the Q for each
> station (based on the Code column). The problem was that I wanted to have
> other column values which were measured for this minimum of the Q.
> I hope my explanation was clear enough. As I said before, I used the Rui's
> codes and I got what I wanted. Although, other solutions provided by others
> were all correct.
>



More information about the R-help mailing list