Movatterモバイル変換


[0]ホーム

URL:


Reshaping panel data withlong_panel() andwiden_panel()

Jacob A. Long

2023-08-21

One of the initial challenges a data analyst is likely to face withpanel data is getting it into a format suitable for analysis. Mostregression analyses for panel data require the data to be inlong format. That means there is a row for each entity(e.g., person) at each time point. If I conducted a 3-wave panel surveyof 300 people, each of whom responded to all 3 waves, the long format ofthese data would have 900 rows (300 respondents x 3 waves).

For example, the following is how long data look, whereid is the identifier for each entity,wave isthe indicator of the time point, andQ1/Q2 aremeasures repeated at each time point.

idwaveQ1Q2
111.05.0
121.57.5
132.010.0
215.014.0
224.010.5
233.07.0
3115.08.0
3212.012.0
339.016.0

Wide data, on the other hand, have only one row perentity and a separate column for each measure and time point. The samedata above in wide format look like this:

idQ1_W1Q1_W2Q1_W3Q2_W1Q2_W2Q2_W3
111.5257.510
254.031410.57
31512.09812.016

Here you differentiate between waves by looking at the column name,which in this case end in “_W” and then the wave indicator. Someanalyses prefer the data in this format, like structural equationmodels.

panelr considers the native format of panel data to belong and provides thepanel_data class to keepyour data tidy in the long format. Of course, sometimes your raw dataaren’t in long format and need to be “reshaped” from wide to long. Inother cases, you have long format data but need to get it into wideformat for some reason or another.panelr provides tools tohelp with these situations.

There are some other tools, including ones thatpanelruses internally, that can manage these situations. However, they tend tobe some combination of confusing, inflexible, or too general to beeasily used for these purposes by non-experts.

From wide to long

In my experience, survey contractors (i.e., the people you pay tocarry out panel surveys) like to provide the data in wide format. As ageneral rule, the conversion of data from wide to long is much moredifficult than the inverse. When preparing to reshape data from wide tolong format, you’ll need to answer some questions relating to how thecolumn/variable names distinguish the variable name from the timeindicator:

One key assumption is that variables labeled with a pattern such asQ1_W1,Q1_W2, and so on refer to thesamemeasure at different times. I’ve encountered datasets in whichQ1 might refer to a different measure at each time pointand this is not a problem that can be handled in an automated way.

With that warning out of the way, let’s look at a coupleexamples.

Wave indicators at the end of variable names

Let’s return to the wide data we looked at earlier.

idQ1_W1Q1_W2Q1_W3Q2_W1Q2_W2Q2_W3
111.5257.510
254.031410.57
31512.09812.016

Here we can see that the time indicators are at theend ofthe variable names (_W1), time indicators of 1, 2, and 3,and aprefix of_W. With that in mind, we can uselong_panel() to convert the data to long format.

long_panel(wide,prefix ="_W",begin =1,end =3,label_location ="end")
idwaveQ1Q2
111.05.0
121.57.5
132.010.0
215.014.0
224.010.5
233.07.0
3115.08.0
3212.012.0
339.016.0

Perfect! The first argument,w, was the wide data.prefix is self-explanatory.begin andend refer to the range of the time indicators, since theyare consecutive. You can instead useperiods = c(1, 2, 3)if you prefer. That’s especially true if you have non-consecutive timeindicators like a biannual survey that uses the year as an indicator,likeperiods = c(1990, 1992, 1994).

Comparing with base R

I should note that base R has a function,reshape() thatcan work in this situation without making you pull your hair out toomuch:

reshape(as.data.frame(wide),sep ="_W",times =c(1,2,3),direction ="long",varying =c("Q1_W1","Q1_W2","Q1_W3","Q2_W1","Q2_W2","Q2_W3"))
idtimeQ1Q2
1.1111.05.0
2.1215.014.0
3.13115.08.0
1.2121.57.5
2.2224.010.5
3.23212.012.0
1.3132.010.0
2.3233.07.0
3.3339.016.0

You can see how frustrating that could be if you had many morevariables — it wouldn’t be unusual to have hundreds of columns in thewide format, not all of which would be variables that vary over time(e.g., race). Truth be told,long_panel() usesreshape() internally, but only after a lot of processing.Other options include thereshape2 andtidyrpackages, but they are not purpose-built for the panel setting andtherefore can have a learning curve to avoid having data that end up abittoo long.

A more challenging example

Here’s a wide dataset with what is usually a trickier format tohandle due to limitations ofreshape().

WA_Q1WB_Q1WC_Q1WA_Q2WC_Q2
11.52510
54.03147
1512.09816

Key characteristics:

While you don’t have to recognize this to use the function properly,notice that in this caseQ2 was only measured at times Aand C. This can add considerable difficulty to when trying to reshapedata “by hand.”

long_panel(wide,prefix ="W",suffix ="_",label_location ="beginning",begin ="A",end ="C")
idwaveQ1Q2
1A1.05
1B1.5NA
1C2.010
2A5.014
2B4.0NA
2C3.07
3A15.08
3B12.0NA
3C9.016

Just what we were looking for. Note thatpanel_dataobjects must have an ordered wave variable, butlong_data()understands how to order letters and handles that for you. Themissingness inQ2 is by design, since it wasn’t measured inwave B.

Another issue that can come up is the treatment of constants — thatis, variables that do not change over time. The best wide data shouldcome labeled in a way that makes it clear the constants are constants.For instance, a variable signifying race wouldn’t be calledrace_W1, but instead justrace.long_panel() automatically checks your data for variablesthat are labeled as if they vary over time but actually do not.

For instance, data that start by looking like this:

idQ1_W1Q1_W2Q1_W3race_W1
111.52white
243.02black
31512.09white

Can easily end up shaped like this:

idwaveraceQ1
11white1.0
12NA1.5
13NA2.0
21black4.0
22NA3.0
23NA2.0
31white15.0
32NA12.0
33NA9.0

But obviously just because the wide data markedracewith a wave label, that doesn’t mean it was unknown in the other waves.You’ll get the right result withlong_panel():

long_panel(wide,prefix ="_W",label_location ="end",begin =1,end =3)
idwaveQ1race
111.0white
121.5white
132.0white
214.0black
223.0black
232.0black
3115.0white
3212.0white
339.0white

Other details

If you have an ID variable in the wide data, you can pass the name ofthat variable tolong_panel() with theidargument, which is"id" by default. If there is no variablewith the name you give toid, one will be created. You canalso choose the name of the wave variable viawave, whichis"wave" by default.

You can also choose not to have the output oflong_panel() be apanel_data object by settingas_panel_data toFALSE.

Advanced options

There are some other options available to you for tougher cases. Forinstance, whenuse.regex isTRUE, thearguments forprefix andsuffix are treated asregular expressions for more complicated patterns.

Internally, time-varying variables are detected by the presence ofprefix, one of the time periods, andsuffix inthe variable name. The “root” variable without the indicator is whateveris left. Sometimes, though, this can cause false matches. Here’s anexample I have encountered. My wide data looked like this:

CaseIDConsentA1B1C1
1TRUE543
2TRUE678
3TRUE1086

My ID variable was calledCaseID and the periods — whichwere A, B, and C — were labeled at thebeginning of the columnnames. Following the earlier examples, this will confuselong_panel():

long_panel(wide,begin ="A",end ="C",label_location ="beginning",id ="CaseID")
CaseIDwave1onsent
1A5TRUE
1B4TRUE
1C3TRUE
2A6TRUE
2B7TRUE
2C8TRUE
3A10TRUE
3B8TRUE
3C6TRUE

See what happened? TheConsent variable in the wide datalooked just like a constant variable that was measured at time point C.This isn’t the end of the world, but errors like this can be moreconfusing and damaging in other scenarios. Fortunately, I knew moreabout the labeling of the time-varying variables than what I toldlong_panel(). Yes, there is A/B/C at the beginning with noprefix/suffix, but also each time-varying item has anumberthat comes after A/B/C.

long_panel() offers the argumentmatch forsituations like these. This is the regular expression used to match andthen capture the variable name sans time indicator. By default,match is".*", meaning any character anynumber of times. To reflect what I know about these data, I change it to"\\d+.*", meaning at least one digit following by anynumber of other characters.

long_panel(wide,begin ="A",end ="C",label_location ="beginning",id ="CaseID",match ="\\d+.*")
CaseIDwaveConsent1
1ATRUE5
1BTRUE4
1CTRUE3
2ATRUE6
2BTRUE7
2CTRUE8
3ATRUE10
3BTRUE8
3CTRUE6

Now it rightly ignoresConsent as a variable that lacksa time indicator. In general,long_panel() tries to protectyou from having to use or even know how to use regular expressions, butsometimes there’s no way around it.

From long to wide

widen_panel(), as you might expect, does the opposite oflong_panel(). This is generally an easier operation,thankfully.

widen_panel() expects apanel_data object.If your long data aren’t in that format, it’s easy enough to just passit topanel_data().

To go through an example, let’s take a look at some long data.

persontimeQ1Q2race
111.05.0white
121.57.5white
132.010.0white
215.014.0black
224.010.5black
233.07.0black
3115.08.0white
3212.012.0white
339.016.0white

Okay, so we have an ID variable (person), wave variable(time), two time-varying variables (Q1 andQ2), and a time-invariant variable (race). Theonly difficulty here conceptually is how to automatically know, withoutthe domain knowledge about the substantive meaning of these variables,which ones vary over time and which don’t. This is simply a matter ofwiden_panel() checking the variance of each (using thepanelr functionare_varying()). Note that invery wide datasets, or those with many individuals, this can take alittle while to happen.

widen_panel(long_data,separator ="_")
personraceQ1_1Q2_1Q1_2Q2_2Q1_3Q2_3
1white151.57.5210
2black5144.010.537
3white15812.012.0916

Pretty much all you need to worry about is how you want to label thewide data. By default theseparator argument is"_".

There are only two other arguments.varying lets youspecify which variables in the long data vary over time. This can saveyou time compared to havingwiden_panel() check them all,but of course requires you to pass those variable names along which canbe more work than it’s worth at times.

ignore.attributes deals with the scenario in which youstarted with wide data, usedlong_panel() to convert tolong format, and now want to convert back to wide format.long_panel() stores information in the data frame aboutwhich variables vary over time so that they don’t have to be checked allover again. If you’ve made changes or think something went wrong, youcan setignore.attributes toTRUE to forcethose checks all over again.


[8]ページ先頭

©2009-2025 Movatter.jp