Compare two rows in one column R
If there are more than two elements per group, do a group by, and create a condition with ifelse/case_when
to create the 'new_var'
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
An option is also to arrange
and then create a new column in the order with rep
(assuming 2 elements per id)
df1 %>%
arrange(id, value) %>%
mutate(new_var = rep(c("lower", "higher"), length.out = n()))
data
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")
We could mutate
a new_var
with an ifelse
statement conditional on min
of value
:
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