Reshape 2 Exercises

August 26, 2016

(This article was first published on R-exercises, and kindly contributed to R-bloggers)

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:

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. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


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)