Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use reshape2 package to convert wide data into long data in r language

Shulou Source: shulou.com Published: 2022-06-01 04:49:54 10月02日 Update

This article mainly introduces the r language how to use reshape2 package to convert wide data into growth data related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this r language how to use reshape2 package to convert wide data into growth data article will have a harvest, let's take a look at it.

Long data vs wide data

For wide data, each column represents a different variable. For example, the mtcars dataset in the datasets package is wide data:

# Wide format mpg cyl disp hp drat wt qsec vs am gear carbMazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4Datsun 710 22.8 4 108 93 3.85 2.320 18.61 11 4 1Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19 . 44 10 3 1Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2Valiant 18.1 6 225 105 2.76 3.460 20.22 10 3 1

For long data, one column contains all possible variables, and the other column is the corresponding value. The above data can be represented by long data:

# Long format variable value1 mpg 21.02 mpg 21.03 mpg 22.84 mpg 21.45 mpg 18.76 mpg 18.1... Variable value347 carb 2348 carb 2349 carb 4350 carb 6351 carb 8352 carb 2

Long data can contain more than two columns, especially when ID variables are provided. As described below.

In practical application, wide data is more readable, while long data is more suitable for analysis. Therefore, it is useful to know how to convert between them.

The two main functions in the reshape2 package are:

Melt-- fuses wide data into growing data.

Cast-- converts long data into wide data

Melt

Next, we operate on the mtcars dataset in the datasets package. It starts with the wide data shown above. We're going to fuse it into the following long data:

Mtcars$car

Tags: Data variables growth type growth type function language parameter result combination knowledge same two content original just formula stronghold article this is faceted Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Tech Info OPPO Reno Shulou Information Xiaomi