Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

r - Use group and row in single term

Let's say I have a single column tibble

a
0
1
2
3
4

where the first three and last two rows are grouped. I would like a tidyverse expression to add two columns with the remaining elements of the group. Thus, I would like

a  b  c
0  1  2
1  0  2
2  0  1
3  4  NA
4  3  NA

Currently, I use something like this

df %>% mutate(b = a[1], c = a[2])

Sadly, this counts the current row as well. How can I exclude the element of the current row?

question from:https://stackoverflow.com/questions/65941006/use-group-and-row-in-single-term

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...