How to usethe gather() method in R Language
Data transformation in R many data columns indicate the values that should be stored in a single column of the data frame and are unnecessarily bifurcated. This can be done using the gather() method. It collects the key-value pairs and rearranges them in new columns. The column values are specified as arguments of the gather() method. For instance, the following code snippet illustrates the combination of col2 to col4 of the data frame under argument 2 of the gather() method. The particular column from which the value was chosen is assigned the tag under the column name “Subject” given by argument 1 of the called method.
Syntax: gather(data, key, value)
The col2, col3, and col4 values in the data frame are clubbed under the column “Subject” in the output data frame. The marks of each student in each subject are then assigned in the col3 value.
R
# Importing dplyr library (dplyr) # Creating a data frame data_frame = data.frame (col1 = c ( "Jack" , "Jill" , "Yash" , "Mallika" , "Muskan" , "Keshav" , "Meenu" , "Sanjay" ), Maths = c (26,47,14,73,65,83,95,48), Physics = c (24,53,45,88,68,35,78,24), Chemistry = c (67,23,79,67,33,66,25,78) ) print ( "Data Frame" ) print (data_frame) data_frame_mutate <- data_frame %>% gather ( "Subject" , "Marks" ,2:4) print ( "Mutated Data Frame" ) # Printing after rearrange data print (data_frame_mutate) |
Output:
col1 Maths Physics Chemistry
1 Jack 26 24 67
2 Jill 47 53 23
3 Yash 14 45 79
4 Mallika 73 88 67
5 Muskan 65 68 33
6 Keshav 83 35 66
7 Meenu 95 78 25
8 Sanjay 48 24 78
[1] "Mutated Data Frame"
col1 Subject Marks
1 Jack Maths 26
2 Jill Maths 47
3 Yash Maths 14
4 Mallika Maths 73
5 Muskan Maths 65
6 Keshav Maths 83
7 Meenu Maths 95
8 Sanjay Maths 48
9 Jack Physics 24
10 Jill Physics 53
11 Yash Physics 45
12 Mallika Physics 88
13 Muskan Physics 68
14 Keshav Physics 35
15 Meenu Physics 78
16 Sanjay Physics 24
17 Jack Chemistry 67
18 Jill Chemistry 23
19 Yash Chemistry 79
20 Mallika Chemistry 67
21 Muskan Chemistry 33
22 Keshav Chemistry 66
23 Meenu Chemistry 25
24 Sanjay Chemistry 78
How to Transform Data in R?
In this article, we will learn how to transform data in the R programming language.
Contact Us