Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - How to use Pivot_longer to reshape from wide-type data to long-type data with multiple variables

I would like to ask how to reshape the following dataframe from wide-type to long-type.

The wide-type data is as follows. Wide-type data before reshaping:
[![Wide-type data before reshaping][1]][1] [1]: https://i.stack.imgur.com/VYQcd.png

The long type data, i.e. the dataframe that I would like to get, is as follows. Long-type data after reshaping:
[![Long-type data after reshaping][2]][2] [2]: https://i.stack.imgur.com/2VpKW.png

Hugely appreciate if you could give me tips to do this using pivot-longer.

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"
)

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.

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

You can try :

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

data

Tried on this data :

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...