Home > Enterprise >  how to pick non zero value in dplyr and retain the sign?
how to pick non zero value in dplyr and retain the sign?

Time:05-23

here is wht my data looks like enter image description here

what i need is the below table

enter image description here

I tried using group_by(id) %>% mutate(col2 = max(abs(col1))) but this unfortunately dosent keep the -ve sign. values in col1 can be both ve and -ve and i need to retain the sign. as suggested by Sotos below, i can use which.max but it will not work in case all the values in a id is 0 in col1. for ids with all vals in col1 = 0, col2 should be 0.

CodePudding user response:

Use which.max() instead, i.e.

library(dplyr)

df %>% 
 group_by(id) %>% 
 mutate(v3 = col1[which.max(abs(col1))])

# A tibble: 12 x 3
# Groups:   id [2]
      id   col1     v3
   <dbl>  <dbl>  <dbl>
 1     1 -33333 -33333
 2     1      0 -33333
 3     1 -33333 -33333
 4     1      0 -33333
 5     1 -33333 -33333
 6     1 -33333 -33333
 7     1 -33333 -33333
 8     1      0 -33333
 9     2      0      0
10     2      0      0
11     2      0      0
12     2      0      0

CodePudding user response:

data.table option:

library(data.table)
setDT(df)
df[, col2 := col1[which.max(abs(col1))], by='id']

Output:

   id   col1   col2
1:  1 -33333 -33333
2:  1      0 -33333
3:  1 -33333 -33333
4:  1      0 -33333
5:  1 -33333 -33333
6:  1 -33333 -33333
7:  1 -33333 -33333
8:  1      0 -33333

Data

df <- data.frame(id = c(1,1,1,1,1,1,1,1),
                 col1 = c(-33333, 0, -33333,0,-33333,0-33333,0-33333,0),
                 col2 = c(0,0,0,0,0,0,0,0))
  • Related