# 比较一列中的两行 R

#### Compare two rows in one column R

``````value   id   new_var
1    1     lower
2    1    higher
5    2    higher
3    2     lower
10    3     lower
11    3    higher
2    4     lower
1    4    higher
``````

2 个回复

``````library(dplyr)
df1 %>%
group_by(id) %>%
mutate(new_var = case_when(value == max(value) ~ "higher",
TRUE ~ "lower")) %>%
ungroup
# A tibble: 8 × 3
value    id new_var
<int> <int> <chr>
1     1     1 lower
2     2     1 higher
3     5     2 higher
4     3     2 lower
5    10     3 lower
6    11     3 higher
7     2     4 higher
8     1     4 lower
``````

``````df1 %>%
arrange(id, value) %>%
mutate(new_var = rep(c("lower", "higher"), length.out = n()))
``````

### 数据

``````df1 <- structure(list(value = c(1L, 2L, 5L, 3L, 10L, 11L, 2L, 1L), id = c(1L,
1L, 2L, 2L, 3L, 3L, 4L, 4L)), row.names = c(NA, -8L), class = "data.frame")
``````

``````library(dplyr)
df %>%
group_by(id) %>%
mutate(new_var = ifelse(value == min(value), "lower", NA_character_)) %>%
ungroup()
``````
``````    value    id new_var
<int> <int> <chr>
1     1     1 lower
2     2     1 NA
3     5     2 NA
4     3     2 lower
5    10     3 lower
6    11     3 NA
7     2     4 NA
8     1     4 lower
``````
2 如何比较R中的两行日期并转换为一行

3 比较两个数据集以查找 r 中的一个数据集中不存在的行 [重复]

2019-11-21 13:28:53 1 46   r
4 比较两个数据帧并通过比较一列找到不在第二个数据帧中的行

2020-01-29 18:21:55 0 71   compare
5 R跨行比较列

2015-10-15 10:51:58 3 484   r/ compare
6 比较R中的两行dataframe

7 比较 R 中的两个列对

2021-10-21 20:25:31 3 40   r
8 根据r中的列值将两行合并为一

2017-07-16 20:16:48 6 2918   r