How to use the names_pattern() argument in pivot_longer()?

Viewed 150

I want to use pivot_longer() to rearrange my dataset and I am aware that I can use the names_pattern argument for this. What I don't fully understand is the syntax (I think?) of this argument.

There are lot of examples online using different symbols like (.), (.*), or (/), ?(.), (.+) and I don't understand when to use what.

As an example, here are the colnames of my wider dataset:

                       "m_Imp", "r_Imp", "t_Imp", "l_Imp", 
                       "m_OD_1", "r_OD_1", "t_OD_1", "l_OD_1", 
                       "m_WS_1", "r_WS_1", "t_WS_1", "l_WS_1", 
                       "m_OD_2", "r_OD_2", "t_OD_2", "l_OD_2",
                       "m_WS_2", "r_WS_2", "t_WS_2", "l_WS_2", 
                       "m_OD_3", "r_OD_3", "t_OD_3", "l_OD_3",
                       "m_WS_3", "r_WS_3", "t_WS_3", "l_WS_3"

The first letter represents a numeric variable, the following 2 or 3 letters represent a certain Process Step and the number in the end stands for a Cycle No. So I would like to have my data is the following format:

Process_Step   Cycle   m      r     t 
OD               1     0.2    5     6
OD               2     0.3    4     7
OD               3     0.25   2     7
Imp              1     0.3    4     9
Imp              2     0.5    4     7
...

The actual data frame is very large, so I hope this example is OK for this question.

Then I tried to use pivot_longer() as follows:

df %>%
  pivot_longer(cols = "m_OD":"l_WS_3",
               names_to = c(".value", "Process_step", "Cycle"),
               names_pattern ="(.)_(..?)_?(.)" )

Which almost works, but I get something like this:

Process_Step   Cycle   m      r     t 
O                D     0.2    5     6
OD               1     0.2    5     6
OD               2     0.3    4     7
OD               3     0.25   2     7
Im               p     0.3    4     9
Im               p     0.5    4     7
                       0.3    4     9
                       0.5    4     7
...

So in some cases the Process Step is mixed up with the Cycle and sometimes empty rows etc.

Can anyone explain how to use the names_pattern argument?

Thanks in advance.

0 Answers
Related