`pivot_longer`操作-实现预期输出的更简单方法? [英] `pivot_longer` operation - simpler way of achieving the expected output?
本文介绍了`pivot_longer`操作-实现预期输出的更简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 df
格式:
df <- tibble(
id = c(1,2,3),
val02 = c(0,1,0),
val03 = c(1,0,0),
val04 = c(0,1,1),
age02 = c(1,2,3),
age03 = c(2,3,4),
age04 = c(3,4,5)
)
我想将其整理成整齐的格式,例如:
I want to bring it into tidy format like:
# A tibble: 9 x 4
id year val age
<dbl> <chr> <dbl> <dbl>
1 1 02 0 1
2 1 03 1 2
3 1 04 0 3
4 2 02 1 2
5 2 03 0 3
6 2 04 1 4
7 3 02 0 3
8 3 03 0 4
9 3 04 1 5
最后使用两个单独的 pivot_longer
操作和 left_join
,我实现了我想要的:
Using two seperate pivot_longer
manipulations with a left_join
at the end I achieved what I want:
library(tidyverse)
df1 <- df %>%
pivot_longer(cols = starts_with("val"), names_to = "year", values_to = "val", names_prefix = "val")
df2 <- df %>%
pivot_longer(cols = starts_with("age"), names_to = "year", values_to = "age", names_prefix = "age")
left_join(df1, df2) %>%
select(id, year, val, age)
但是,这似乎非常复杂.
This, however, seems utterly complicated.
如何简化此操作?有一种方法可以一次性执行此操作吗?(在一个管道中..?)
推荐答案
这取决于您的字符串(列名)的复杂程度,但要给出一个主意:
This depends on the complexity of your strings (column names), but to give an idea:
library(tidyverse)
df %>%
pivot_longer(-id,
names_to = c('.value', 'year'),
names_pattern = '([a-z]+)(\\d+)'
)
输出:
# A tibble: 9 x 4
id year val age
<dbl> <chr> <dbl> <dbl>
1 1 02 0 1
2 1 03 1 2
3 1 04 0 3
4 2 02 1 2
5 2 03 0 3
6 2 04 1 4
7 3 02 0 3
8 3 03 0 4
9 3 04 1 5
这篇关于`pivot_longer`操作-实现预期输出的更简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文