first we generate the data frame with a defined grouping:
df = data.frame(a=0:4,grp=rep(1:2,c(3,2)))
a grp
1 0 1
2 1 1
3 2 1
4 3 2
5 4 2
Then we group by the group and use a map()
with setdiff
to get the other elements. Next we explode this and then pivot wide again. There might be some easier way but this is what I can come up with:
library(dplyr)
library(purrr)
library(tidyr)
df %>% group_by(grp) %>%
mutate(other = map(a,~setdiff(a,.x))) %>%
unnest(other) %>%
group_by(a,grp) %>%
mutate(id = 1:n()) %>%
ungroup() %>%
pivot_wider(id_cols=a,names_from=id,values_from=other)
# A tibble: 5 x 3
a `1` `2`
<int> <int> <int>
1 0 1 2
2 1 0 2
3 2 0 1
4 3 4 NA
5 4 3 NA
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…