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
CodePudding user response:
You could do this as a one-liner in base R. Use rank
to get the order each entry takes, find which rank is below 4, then use ifelse
to select 't' or 'f' based on this.
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")
CodePudding user response:
library(dplyr)
df <- data.frame(
x = c(3L, 14L, 1L, 7L),
y = c("f", "f", "f", "f")
)
df %>%
mutate(
y = case_when(
x == sort(x)[1] ~ "t",
x == sort(x)[2] ~ "t",
x == sort(x)[3] ~ "t",
TRUE ~ "f"
)
)
#> x y
#> 1 3 t
#> 2 14 f
#> 3 1 t
#> 4 7 t
Created on 2022-07-12 by the reprex package (v2.0.1)
CodePudding user response:
Just arrange the dataframe in ascending order of x, then edit the y value for the first three rows.
data <- data[order(x),]
for (i in 1:3) {
data$x[i] <- 't'
}