Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

FInd max Value by multiple colums as new column [duplicate]

$
0
0

I have a df like this:

x = c(1,1,2,2,1 ) 
y = c(2,2,3,3,1 ) 
z = c(4,3,2,1,1 ) 
df<-data.frame(x,y,z)

Now I have to find the max value in column z. My Output should looks like this:

      x y z max
      1 2 4 4
      1 2 3 4
      2 3 2 2
      2 3 1 2
      1 1 1 1

All columns and rows should be preserved. With max() solutions or grouping or filter() I always get only a subset.

Update:

I tried the solution with:

df$max <- apply(df, 1, max

But then the ouput is:

  x y z max
1 1 2 4   4
2 1 2 3   3
3 2 3 2   3
4 2 3 1   3
5 1 1 1   1

When I do:

df2 %>% group_by(x, y,) %>% summarise(max_z= max(z))

I get a subset:

# A tibble: 2 x 3
# Groups:   x [2]
      x     y max_z
  <dbl> <dbl> <dbl>
1     1     2     4
2     2     3     2

Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>