How to spread rows of multiple columns at once and gather them?

Creating multiple columns using spread function from the dplyr package is straightforward.
For example, I can use this: spread(df, key = 'var1', value = 'estimate')

How can we do if we have rows of multiple columns (var1 to var5) as an example below? This gives duplicate columns, which is also a big issue I am concerned about.
I will then gather them together and wondering how will this be done.

id var1 var2 var3 var4 var5 estimate
1 A B C 1
2 B A C D E 1
3 C D E 1
4 A B E 1
5 D E F 1
6 B C D E F 1
7 A B C D F 1
8 F G 1
9 G H 1
10 D F K 1

Thanks

pivot_longer(df,
             c(var1:var5)) %>% filter(
               value != ''
             ) %>%
  pivot_wider(id_cols=id,
              names_from=value,
              values_from=estimate,
              values_fn=length)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.