Home > Enterprise >  I need to replace some value of a columen by minimum value of that column for specific ids
I need to replace some value of a columen by minimum value of that column for specific ids

Time:03-11

data<-data.frame(id=c(1,1,1,1, 2,2,2,2, 3,3,4,4,4), 
                 x1=c(20,26,23,25,20,19,24,18,19,21,24,21,26),
                 x2=c(2,5,4,3,2,5,4,8,4,6,2,5,6),
                 x3=c("yes", "no", "yes", "no", "no", "yes" , "yes", "no", "yes", "no", "yes", "yes", "yes"))
library(dplyr)
df<-filter(data, data$x1>23) 

For this filtered data, the minimum value of data is 2 or min(df$x2)=2 then I need to replace the value of x2 for filtered id with 2.

The desired output is:

   id x1 x2  x3
1   1 20  2 yes
2   1 26  2  no
3   1 23  4 yes
4   1 25  2  no
5   2 20  2  no
6   2 19  5 yes
7   2 24  2 yes
8   2 18  8  no
9   3 19  4 yes
10  3 21  6  no
11  4 24  2 yes
12  4 21  5 yes
13  4 26  2 yes

I tried as

library(dplyr)
dat1a <- data %>% replace(x2,  min(filter(data, data$x1>23)$x2))

CodePudding user response:

We may use replace within mutate

library(dplyr)
data <- data %>% 
   mutate(x2 = replace(x2, x1 > 23, min(x2[x1 > 23])))

-output

 id x1 x2  x3
1   1 20  2 yes
2   1 26  2  no
3   1 23  4 yes
4   1 25  2  no
5   2 20  2  no
6   2 19  5 yes
7   2 24  2 yes
8   2 18  8  no
9   3 19  4 yes
10  3 21  6  no
11  4 24  2 yes
12  4 21  5 yes
13  4 26  2 yes
  • Related