library(tidyverse)
dat <- tibble(
from = c("A", "A", "C", "C"),
to = c("B", "B", "D", "D")
)
sol <- dat %>%
mutate(
fst = lag(from), # lag `from` for first values
lst = lead(from) # lead `from` for last values
) %>%
group_by(from) %>%
transmute(
to = case_when(
row_number() == 1 & !is.na(fst) ~ fst, # if first element in group and lagged `from` is not NA then equals lagged `from`
row_number() == n() & !is.na(lst) ~ lst, # if last element in group and leaded `from` is not NA, then equals leaded `from`
T ~ to # else `to`
)
) %>%
ungroup()
sol
#> # A tibble: 4 × 2
#> from to
#> <chr> <chr>
#> 1 A B
#> 2 A C
#> 3 C A
#> 4 C D
3条答案
按热度按时间qco9c6ql1#
获取您想要更改的值的索引(无需分组),并将其替换为
rev
ersed值:输出
odopli942#
使用
base R
66bbxpm53#
下面是一个
tidyverse
解决方案: