Reshape 2 Exercises

[This article was first published on R-exercises, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

ice-cubes-1224804_960_720The Reshape 2 package is based on differentiating between identification variables, and measurement variables. The functions of the Reshape 2 package then “melt” datasets from wide to long format, and “cast” datasets from long to wide format.

Required package:
library(reshape2)

Answers to the exercises are available here.

Exercise 1

Set a variable called “moltenMtcars“, by using the melt() function to format “mtcars” to long format using the id variables, “cyl” and “gear“.

Exercise 2

Set a variable, “CarSurvey“, using dcast() to reformat “moltenMtcars” to wide format, with “cyl” and “gear” in the first two columns. The aggregation function is “mean“.

Exercise 3

Using the melt() function, format “airquality” with 1 measurement per Month/Day date. Set a variable called “weatherSurvey“.

Exercise 4

Specify the name of “weatherSurvey” column 4 as “Condition“, and the name of column 5 as “Measurement“, using the melt() formula in Exercise 3.

Exercise 5

Use dcast() to format “weatherSurvey” from long to wide, with Month and Day as the first 2 columns. Set a new variable, “airqualityEdit“.

Exercise 6

acast() converts a long-format “molten” data frame into a wide-format vector/matrix/array.

Set a new variable, “AirQualityArray“, via using acast() to re-format, “weatherSurvey“, by Day, Month, and Condition.

Exercise 7

Use the acast() function to get the means of “weatherSurvey” measurement variables by month. Also, remove not available values.

Exercise 8

Use the “margins =” parameter of acast() in order to include the means of all measurement variables in the formula from Exercise 7.

Exercise 9

Use the recast() function to combine the melt() operation from Exercise 1, and the dcast() operation from Exercise 2.

Exercise 10

Use the recast() function to combine the melt() operation from Exercise 4, and the dcast() operation from Exercise 5. Return the first 5 rows.

To leave a comment for the author, please follow the link and comment on their blog: R-exercises.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)