[英]Change 3 rows which have the smallest value among all values in R
I have a data that looks like this我有一个看起来像这样的数据
x X | y是的 |
---|---|
3 3 | f F |
14 14 | f F |
1 1 | f F |
7 7 | f 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
值最低的 3 个个体的y
值从f
更改为t
,这样我的数据将如下所示:
| x | y |
|:---:|:---:|
| 3 | t |
| 14 | f |
| 1 | t |
| 7 | t |
Kind regards亲切的问候
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.您可以将其作为基础 R 中的单行来执行。使用rank
获取每个条目的顺序,找到哪个 rank 低于 4,然后使用ifelse
根据此选择“t”或“f”。
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")
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)由reprex 包创建于 2022-07-12 (v2.0.1)
Just arrange the dataframe in ascending order of x, then edit the y value for the first three rows.只需按 x 的升序排列数据框,然后编辑前三行的 y 值。
data <- data[order(x),]
for (i in 1:3) {
data$x[i] <- 't'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.