Uploaded by Muhammad Wasi

chap 9.-1 R exercises 3

advertisement
2023/6/27
R Exercises 3
1
 Reshaping Data
○ There are two types of format: wide format and long (or molten) format.
2
> Honeymoon.Period <- read.delim("~/R/data/22F data/Honeymoon
Period.dat")
Wide format
3
Long format
4
 The change between wide and long data formats can be done with melt() and cast()
command from the reshape package. Or for simple data sets we can use stack() and
unstack().
 Stack() and unstack()
> Stacked <- stack(Honeymoon.Period, select = c("Satisfaction_Base",
"Satisfaction_6_Months", "Satisfaction_12_Months",
"Satisfaction_18_Months"))
> Stacked
values
ind
1
6
Satisfaction_Base
2
7
Satisfaction_Base
3
4
Satisfaction_Base
4
6
Satisfaction_Base
5
6
Satisfaction_Base
6
5
Satisfaction_Base
7
6
Satisfaction_Base
8
2
Satisfaction_Base
9
10
Satisfaction_Base
10
10
Satisfaction_Base
unstacked <- unstack(Stacked)
> unstacked
1
2
3
4
5
Satisfaction_Base Satisfaction_6_Months Satisfaction_12_Months Satisfaction_18_Months
6
7
4
6
6
6
7
6
9
7
5
8
2
4
6
2
4
2
1
6
5
6
7
8
9
10
11
12
13
14
15
5
6
2
10
10
8
6
7
6
9
10
6
5
9
10
8
10
8
7
10
4
4
4
5
10
10
9
9
9
8
2
2
NA
6
9
9
9
6
5
6
 The stack() and unstack() functions are fine for simple operations. But to gain
more control of the data restructuring we should use reshape package.
> install.packages(“reshape”)
> library(reshape)
> newFrame <- melt(Honeymoon.Period, id = c("Person", "Gender"),
measured = c("Satisfaction_Base", "Satisfaction_6_Months",
"Satisfaction_12_Months", "Satisfaction_18_Months"))
> head(newFrame)
Person Gender
variable value
1
1
0 Satisfaction_Base
6
2
2
1 Satisfaction_Base
7
3
3
1 Satisfaction_Base
4
4
4
0 Satisfaction_Base
6
5
5
0 Satisfaction_Base
6
6
6
1 Satisfaction_Base
5
6
> wideData <- cast(newFrame, Person + Gender ~variable, value =
"value")
> head(wideData)
Person Gender Satisfaction_Base Satisfaction_6_Months Satisfaction_12_Months Satisfaction_18_Months
1
2
3
4
5
6
1
2
3
4
5
6
0
1
1
0
0
1
6
7
4
6
6
5
6
7
6
9
7
10
5
8
2
4
6
4
2
4
2
1
6
2
>
7
Download