如何使用 Pivot_longer 将宽型数据重塑为具有多个变量的长型数据 [英] How to use Pivot_longer to reshape from wide-type data to long-type data with multiple variables
问题描述
我想问一下如何将下面的dataframe从宽型改成长型.
I would like to ask how to reshape the following dataframe from wide-type to long-type.
宽型数据如下.整形前的宽型数据长型数据,即我想得到的数据帧,如下.整形后的长型数据如果您能给我使用 Pivot-longer 的提示,我将不胜感激.
The wide-type data is as follows. Wide-type data before reshaping The long type data, i.e. the dataframe that I would like to get, is as follows. Long-type data after reshaping Hugely appreciate if you could give me tips to do this using pivot-longer.
我可以通过编写 BLS 和 ELS 分别重塑数据:
I could reshape the data separately by BLS and ELS by writing :
df_long_BLS <- df %>%
pivot_longer(
cols = starts_with("BLS_tchrG"),
names_to = "grade",
names_prefix = "BLS_tchrG",
values_to = "BLS_tchrG"
)
df_long_ELS <- df %>%
pivot_longer(
cols = starts_with("ELS_tchrG"),
names_to = "grade",
names_prefix = "ELS_tchrG",
values_to = "ELS_tchrG"
)
但是这样我需要合并两个单独的文件.我想知道如何在不制作 2 个单独文件的情况下进行此数据重塑.
But in this way I need to merge the 2 separate files. I would like to know how to do this data reshape without making 2 separate files.
非常感谢,
推荐答案
你可以试试:
tidyr::pivot_longer(df, cols = -ID_IE,
names_to = c('.value', 'grade'),
names_pattern = '(.*)(\\d+)')
# A tibble: 8 x 4
# ID_IE grade BLS_tchrG ELS_tchrG
# <dbl> <chr> <dbl> <dbl>
#1 2135 2 1 1
#2 2135 7 1 1
#3 2101 2 0 0
#4 2101 7 2 0
#5 2103 2 0 0
#6 2103 7 3 0
#7 2111 2 1 1
#8 2111 7 4 1
数据
尝试使用此数据:
df <- data.frame(ID_IE = c(2135, 2101, 2103, 2111), BLS_tchrG2 = c(1, 0, 0, 1),
BLS_tchrG7 = 1:4,
ELS_tchrG2 = c(1, 0, 0, 1), ELS_tchrG7 = c(1, 0, 0, 1))
这篇关于如何使用 Pivot_longer 将宽型数据重塑为具有多个变量的长型数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!