Wide To Long Form data in R

Wide To Long Form data in R, To pivot a data frame from a wide to a long format, use the pivot longer() function from the tidyr package in R.

The following is the fundamental syntax for this function.

Random Forest Feature Selection » Boruta Algorithm » finnstats

library(tidyr)
df %>% pivot_longer(cols=c('var1', 'var2', ...),
                    names_to='col1_name',
                    values_to='col2_name')

where:

cols: The names of the pivot columns
names_to: The new character column's name
values_to: The new values column's name is

Wide To Long Form data in R

Let’s create a wide data frame first,

df <- data.frame(team=c('Q1', 'Q2', 'Q3', 'Q4', 'Q5'),
                 kick=c(13, 18, 31, 32, 14),
                 pass=c(32, 22, 23, 34, 35))
df
  team kick pass
1   Q1   13   32
2   Q2   18   22
3   Q3   31   23
4   Q4   32   34
5   Q5   14   35

To pivot this data frame into a long format, we can use the pivot longer() function.

How to Calculate Cramer’s V in R » finnstats

library(tidyr)

the data frame is pivoted into a long format

df %>% pivot_longer(cols=c('kick', 'pass'),
                    names_to='kick',
                    values_to='points')
   team kick points
1    Q1 kick     13
2    Q1 pass     32
3    Q2 kick     18
4    Q2 pass     22
5    Q3 kick     31
6    Q3 pass     23
7    Q4 kick     32
8    Q4 pass     34
9    Q5 kick     14
10   Q5 pass     35

The values from these original columns are now placed in a single new column named “points,” and the column names kick and pass are now utilized as values in a new column called “kick.”

How to Split data into train and test in R » finnstats

A lengthy data frame is the end result. For more information, you can find it here.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *