2

I have 3 columns of xyz data. The points are regulary spaced in x and y direction. I would like to find out the max value of z for each step of x. I was able to do this for one "x" value which I specifically assigned, but as there are a lot more, I created a vector (vecx) by using function unique() with all possible values inside. Unfortunately I was not able to assign it correctly, as only the value that matches the overall max value of z was picked (which is logical). I am not sure if there is a easy solution by just using a grouping funktion for the x values instead of my way of using a vector?

xyzmax <- xyz[x %in%vecx ][which.max(z)]

This is a short preview of the data(x,y and z are labels of the columns in xyz:

     x        y    z
  1. 1810.0 5932.200 4767
  2. 1810.0 5982.108 4746
  3. 1810.0 6032.015 4717
  4. 1856.5 5483.031 4736
  5. 1856.5 5532.938 4738
  6. 1856.5 5582.846 4746
  7. 1856.5 5632.754 4742
  8. 1856.5 5682.662 4752
  9. 1856.5 5732.569 4756

and this is what it should look like, after running the code:

         x        y       z
  1. 1810.0 5932.200 4767
  2. 1856.5 5732.569 4756

As there are hundreds of x values and the values are changing with resolution of the point grid. That is why I am not keen to enter them by hand or create tables for single values which is done in similar questions. I just started to work with R and would be thankful for any kind of help!

Prany
  • 2,078
  • 2
  • 13
  • 31
morgun
  • 21
  • 3

1 Answers1

2

data.table

library(data.table)
setDT(df)
df[, .SD[which.max(z)], by = x]

#         x        y    z
# 1: 1810.0 5932.200 4767
# 2: 1856.5 5732.569 4756

dplyr

library(dplyr)
df %>% 
  group_by(x) %>% 
  slice(which.max(z))

Data used:

df <- fread("
   x        y    z
1810.0 5932.200 4767
1810.0 5982.108 4746
1810.0 6032.015 4717
1856.5 5483.031 4736
1856.5 5532.938 4738
1856.5 5582.846 4746
1856.5 5632.754 4742
1856.5 5682.662 4752
1856.5 5732.569 4756
")
IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38