[英]How do I create a new column for every pair of observations in each row - R Language
I would like to change my tibble so that every observation gets paired with the following observation into a new row, while retaining the id.我想更改我的 tibble,以便每个观察都与以下观察配对成一个新行,同时保留 id。
x1 <- c("cook", "clean", "wash", "walk", "wish", "broom", "clean", "wash", "walk", "cook")
x2 <- c("move", "climb", "skate", "ball", "climb", "jog", "job", "skate", "ball", "climb")
x3 <- c("try", "clean", "boom", "walk", "bring", "broom", "sing", "wash", "jump", "fly")
df <- tibble(y, x1, x2, x3)```
In this situation,
```row 1 should be: y=1, x1="cook", x2="move"
row 2 should be: y=1, x2="move", x3="try"
row 3 should be: y=2, x1="clean", x2="climb"
row 4 should be: y=2, x2="climb", x3="clean"```
I might have to iterate the process where the number of observations "x" is roughly equal to 50.
Thank you so much for the help!
Re-reading your question, I realize you need it to work for x1, x2 ... x50
, so I've rewritten the answer to be more flexible.重新阅读您的问题,我意识到您需要它为x1, x2 ... x50
,所以我重写了答案以使其更加灵活。 Just include x1:x50
in the pivot_longer
call instead of x1:x3
.只需在pivot_longer
调用中包含x1:x50
而不是x1:x3
。
df %>%
pivot_longer(names_to="obs", values_to="val", x1:x3) %>%
group_by(y) %>%
mutate(x1 = val, x2 = lead(val)) %>%
filter(!is.na(x2)) %>%
select(y, x1, x2)
Output:输出:
# A tibble: 20 x 3
# Groups: y [10]
y x1 x2
<int> <chr> <chr>
1 1 cook move
2 1 move try
3 2 clean climb
4 2 climb clean
5 3 wash skate
6 3 skate boom
7 4 walk ball
8 4 ball walk
9 5 wish climb
10 5 climb bring
11 6 broom jog
12 6 jog broom
13 7 clean job
14 7 job sing
15 8 wash skate
16 8 skate wash
17 9 walk ball
18 9 ball jump
19 10 cook climb
20 10 climb fly
Is this the pattern you need?这是你需要的模式吗?
df %>%
bind_rows(df) %>%
arrange(y) %>%
group_by(y) %>%
mutate(x1_new = if_else(row_number() == 1, x1, x2),
x2_new = if_else(row_number() == 1, x2, x3)) %>%
select(y, x1_new, x2_new)
Output:输出:
# A tibble: 20 x 3
# Groups: y [10]
y x1_new x2_new
<int> <chr> <chr>
1 1 cook move
2 1 move try
3 2 clean climb
4 2 climb clean
5 3 wash skate
6 3 skate boom
7 4 walk ball
8 4 ball walk
9 5 wish climb
10 5 climb bring
11 6 broom jog
12 6 jog broom
13 7 clean job
14 7 job sing
15 8 wash skate
16 8 skate wash
17 9 walk ball
18 9 ball jump
19 10 cook climb
20 10 climb fly
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.