| Start | |||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Reshaping data Often data comes in tables. Generally one can divide this tabular data in wide and long formats. In a wide format, each variable has its own column.
However, sometimes it is more convenient to have a long format, in which all variables are in one column and the values are in a second column.
Base R, as well as third party packages can be used to simplify this process. For each of the options, the Base RThere are two functions in base R that can be used to convert between wide and long format: However, these functions can become very complex for more advanced use cases. Luckily, there are other options using third party packages. The tidyr packageThis package uses The data.table packageThe data.table package extends the |
|||||||||||||||||||||||||||||||||
| The reshape function The most flexible base R function for reshaping data is Note that the data.frame is unbalanced, that is, unit 2 is missing an observation in the first period, while units 3 and 4 are missing observations in the second period. Also, note that there are two variables that vary over the periods: counts and values, and two that do not vary: identifier and location. Long to WideTo reshape the data.frame to wide format, Notice that the missing time periods are filled in with NAs. In reshaping wide, the "v.names" argument specifies the columns that vary over time. If the location variable is not necessary, it can be dropped prior to reshaping with the "drop" argument. In dropping the only non-varying / non-id column from the data.frame, the v.names argument becomes unnecessary. Wide to LongTo reshape long with the current df.wide, a minimal syntax is However, this is typically trickier: Now the simple syntax will produce an error about undefined columns. With column names that are more difficult for the In reshaping long, the "v.names" argument can be provided to rename the resulting varying variables. Sometimes the specification of "varying" can be avoided by use of the "sep" argument which tells RemarksHelpful packages
|
Read Article
https://develop.horje.com/learn/1434/reference