Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading