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

Change 3 rows which have the smallest value among all values in R

I have a data that looks like this

x y
3 f
14 f
1 f
7 f

What I want is to change the y value of 3 individuals with the lowest x value from f to t so my data would look like this:


|  x  |  y  |
|:---:|:---:|
|  3  |  t  |
|  14 |  f  |
|  1  |  t  |
|  7  |  t  |

Kind regards

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

>Solution :

You could do this as a one-liner in base R:

within(df, y <- ifelse(rank(x) < 4, "t", "f"))
#>    x y
#> 1  3 t
#> 2 14 f
#> 3  1 t
#> 4  7 t

Data taken from question

df <- data.frame(x = c(3, 14, 1, 7), y = "f")
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