Find max value in a column and creating a new dataframe with that row plus 15 rows above and below

Hi everyone,

I am fairly new to RStudio, but essentially what I am trying to do is first find the maximum value in a certain column (and I want to keep all the associated data that goes along with it in the same row). Then I want to create a new dataframe with the maximum value data and incorporate the row data 15 rows above the maximum and 15 rows below that maximum. I would appreciate any suggestions as to how to approach this problem. Thanks!

Here is one method.

library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2
set.seed(123)
DF <- data.frame(Names = sample(LETTERS, 100, replace = TRUE),
                 Value = rnorm(100))
max(DF$Value)
#> [1] 1.871418
RowWithMax <- which(DF$Value == max(DF$Value))
Before15 <- RowWithMax - 15
After15 <- RowWithMax + 15
NewDF <- slice(DF, Before15:After15)
NewDF
#>    Names        Value
#> 1      Y -0.230262235
#> 2      B  1.397426653
#> 3      E  1.763653031
#> 4      H  0.485601354
#> 5      L -0.265738944
#> 6      M  0.151611371
#> 7      R  1.376609813
#> 8      A -0.180394314
#> 9      Y -1.567675132
#> 10     Y -0.260725893
#> 11     F  0.961810352
#> 12     U  0.853895464
#> 13     O  0.418796702
#> 14     I  0.339956513
#> 15     O  0.596425059
#> 16     Z  1.871418005
#> 17     P  0.602870370
#> 18     T -0.766168804
#> 19     F -0.620326487
#> 20     K  0.790190251
#> 21     H -0.241976510
#> 22     V  1.117486481
#> 23     V  1.184930635
#> 24     G  1.646474838
#> 25     P  0.192996186
#> 26     Q -0.392553554
#> 27     V  0.007051323
#> 28     R -2.494835444
#> 29     Q -0.977296362
#> 30     B  0.628568823
#> 31     D -0.084140473

Created on 2022-03-30 by the reprex package (v2.0.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.