Flexibly Reshape Data: A Reboot of the Reshape Package

Flexibly restructure and aggregate data using just two functions: melt and 'dcast' (or 'acast').

Build Status Coverage status



reshape2 is retired: only changes necessary to keep it on CRAN will be made. We recommend using tidyr instead.


Reshape2 is a reboot of the reshape package. It's been over five years since the first release of reshape, and in that time I've learned a tremendous amount about R programming, and how to work with data in R. Reshape2 uses that knowledge to make a new package for reshaping data that is much more focused and much much faster.

This version improves speed at the cost of functionality, so I have renamed it to reshape2 to avoid causing problems for existing users. Based on user feedback I may reintroduce some of these features.

What's new in reshape2:

  • considerably faster and more memory efficient thanks to a much better underlying algorithm that uses the power and speed of subsetting to the fullest extent, in most cases only making a single copy of the data.

  • cast is replaced by two functions depending on the output type: dcast produces data frames, and acast produces matrices/arrays.

  • multidimensional margins are now possible: grand_row and grand_col have been dropped: now the name of the margin refers to the variable that has its value set to (all).

  • some features have been removed such as the | cast operator, and the ability to return multiple values from an aggregation function. I'm reasonably sure both these operations are better performed by plyr.

  • a new cast syntax which allows you to reshape based on functions of variables (based on the same underlying syntax as plyr):

  • better development practices like namespaces and tests.

  • the function melt now names the columns of its returned data frame Var1, Var2, ..., VarN instead of X1, X2, ..., XN.

  • the argument variable.name of melt replaces the old argument variable_name.

Initial benchmarking has shown melt to be up to 10x faster, pure reshaping cast up to 100x faster, and aggregating cast() up to 10x faster.

This work has been generously supported by BD (Becton Dickinson).


  • Get the released version from cran: install.packages("reshape2")
  • Get the dev version from github: devtools::install_github("hadley/reshape")


Version 1.4.3

  • Fix C/C++ problems causing R CMD CHECK errors.

  • melt.data.frame() throws when encountering objects of type POSIXlt, and requests a conversion to the (much saner) POSIXct type.

Version 1.4.2

  • Minor R CMD check fixes for CRAN.

Version 1.4.1

  • melt.data.frame() now properly sets the OBJECT bit on value variable generated if attributes are copied (for example, when multiple POSIXct columns are concatenated to generate the value variable) (#50)

  • melt.data.frame() can melt data.frames containing list elements as id columns. (#49)

  • melt.data.frame() no longer errors when measure.vars is NULL or empty. (#46)

Version 1.4

  • dcast() and acast() gain a useful error message if you use value_var intead of value.var (#16), and if value.var doesn't exist (#9). They also work better with . in specifications like . ~ . or x + y ~ .

  • melt.array() creates factor variables with levels in the same order as the original rownames (#19)

  • melt.data.frame() gains an internal Rcpp / C++ implementation, and is now many orders of magnitudes faster. It also preserves identical attributes for measure variables, and now throws a warning if they are dropped. (Thanks to Kevin Ushey)

  • melt.data.frame() gains a factorsAsStrings argument that controls whether factors are converted to character when melted as measure variables. This is TRUE by default for backward compatibility.

  • melt.array() gains a as.is argument which can be used to prevent dimnames being converted with type.convert()

  • recast() now returns a data frame instead of a list (#45).

Version 1.2.2

  • Fix incompatibility with plyr 1.8

  • Fix evaluation bug revealed by knitr. (Fixes #18)

  • Fixed a bug in melt where it didn't automatically get variable names when used with tables. (Thanks to Winston Chang)

Version 1.2.1

  • Fix bug in multiple margins revealed by plyr 1.7, but caused by mis-use of data frame subsetting.

Version 1.2

  • Fixed bug in melt where factors were converted to integers, instead of to characters

  • When the measured variable is a factor, dcast now converts it to a character rather than throwing an error. acast still returns a factor matrix. (Thanks to Brian Diggs.)

  • acast is now much faster, due to fixing a very slow way of naming the output. (Thanks to José Bartolomei Díaz for the bug report)

  • value_var argument to acast and dcast renamed to value.var to be consistent with other argument names

  • Order NA factor levels before (all) when creating margins

  • Corrected reshape citation.

Version 1.1

  • melt.data.frame no longer turns characters into factors

  • All melt methods gain a na.rm and value.name arguments - these previously were only possessed by melt.data.frame (Fixes #5)

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.


1.4.4 by Hadley Wickham, 2 years ago


Report a bug at https://github.com/hadley/reshape/issues

Browse source code at https://github.com/cran/reshape2

Authors: Hadley Wickham <[email protected]>

Documentation:   PDF Manual  

MIT + file LICENSE license

Imports plyr, Rcpp, stringr

Suggests covr, lattice, testthat

Linking to Rcpp

Imported by ABHgenotypeR, AGread, ANN2, AppliedPredictiveModeling, ArchaeoPhases, AvInertia, BACCT, BAwiR, BBEST, BCEA, BEKKs, BTSPAS, BacArena, BayesCTDesign, BayesPostEst, BayesSPsurv, BayesianReasoning, BinarybalancedCut, C443, CANSIM2R, CAinterprTools, CMapViz, CNVScope, COINr, CSTools, CSUV, CalibratR, ChemoSpec, CityWaterBalance, ClimClass, ClussCluster, ClustAssess, Cluster.OBeu, CoDiNA, CopulaDTA, CropDetectR, Cubist, DGM, DVHmetrics, DataExplorer, DataVisualizations, DeLorean, DeductiveR, DescribeDisplay, DramaAnalysis, EEM, EFA.MRFA, EasyHTMLReport, EloOptimized, EpiDynamics, EpiEstim, EstimDiagnostics, EvaluateCore, EvolutionaryGames, Evomorph, FRK, FinCal, ForeCA, ForecastTB, FreqProf, FuncNN, G2Sd, GCalignR, GEInter, GMSimpute, GREENeR, GenHMM1d, GetDFPData, GuessCompx, HH, HLMdiag, HRM, HS, HaDeX, HierDpart, HuraultMisc, IATscores, IDSA, IMTest, IOHanalyzer, IPV, ITNr, InterfaceqPCR, Irescale, L0Learn, LMMstar, LOMAR, LPRelevance, LSX, LambertW, LongDat, MBNMAdose, MBNMAtime, MHMM, MLZ, MMVBVS, MPTmultiverse, MRFcov, MSRDT, MSbox, MSclassifR, MarketMatching, MetaClean, MetaComp, MetaDBparse, MetaIntegrator, MixSIAR, MultIS, NMADiagT, NMAoutlier, NMF, NMproject, NPBayesImputeCat, NPflow, NetworkComparisonTest, NeuralNetTools, NeuralSens, OmicInt, OpasnetUtils, OpenRepGrid.ic, OptCirClust, PAutilities, PCADSC, PLMIX, PTXQC, PWFSLSmoke, PhenotypeSimulator, Plasmidprofiler, Platypus, PlotPrjNetworks, PolicyPortfolios, R3port, RAM, RDS, RNeXML, RSSL, RStoolbox, RTIGER, RareComb, Rata, RcmdrPlugin.FuzzyClust, RelimpPCR, RepertoiR, RichR, Rirt, Rmst, RobKF, Rwtss, SBMSplitMerge, SCORPIUS, SEERaBomb, SLEMI, SSDL, SSDM, STMedianPolish, STMotif, SUMMER, SVMMaj, SWIM, SWMPr, SWTools, SensoMineR, ShinyQuickStarter, SixSigma, SlaPMEG, SleepCycles, SoundShape, SourceSet, SoyNAM, StMoMo, Statsomat, Superpower, TCIU, TSMining, TSstudio, TcGSA, Tendril, TopDom, TripleR, TropFishR, UPG, Umatrix, VDAP, ViSiElse, WINS, aLFQ, actel, adegenet, advclust, afex, aiRly, ammistability, animint2, anomaly, aslib, assignPOP, atable, augmentedRCBD, backShift, bayefdr, bayesPop, bayesdfa, bayesplot, bayesvl, baystability, beezdemand, bikm1, bioassays, blrm, bmmix, bmotif, bnmonitor, boral, bulletr, burnr, cancerGI, caret, cartograflow, cassandRa, causalPAF, cellWise, changepoint.mv, childsds, chillR, clhs, clifro, clustMD, coefplot, communication, conText, conos, cooccur, corona, cplm, critpath, csa, csodata, cutoffR, dampack, data360r, dataprep, dbhydroR, dbmss, deconstructSigs, dendroTools, denovolyzeR, desplot, detectRUNS, devtoolbox, difNLR, diffEnrich, diffudist, digitalDLSorteR, do, drfit, drimmR, drpop, dsa, dtwSat, dtwclust, dynRB, dynfeature, dynplot, dynr, dynwrap, eSIR, eat, eatRep, econullnetr, ecr, edina, effectR, elaborator, elasticIsing, emdi, enpls, ensembleTax, entropart, epinetr, ethnobotanyR, etrm, evolqg, expDB, exreport, ez, fSRM, fabisearch, factoextra, factorMerger, fcm, fdaPOIFD, fdapaceShiny, fergm, fmriqa, foqat, foster, frailtySurv, freesurfer, funModeling, gWQS, gdm, genBaRcode, genius, genotypeR, geocmeans, ggcorrplot, gge, ggenealogy, ggiraphExtra, gglogo, ggparallel, ggrisk, ghypernet, glmmPen, glmmfields, grabsampling, granovaGG, grapesAgri1, grapherator, gridsampler, growfunctions, gstar, gumboot, hJAM, handwriter, hazus, heatmaply, hlaR, hybridModels, hydraulics, hydroToolkit, hydrotoolbox, hyfo, iCARH, iNEXT, icardaFIGSr, immcp, immunarch, immuneSIM, imputeR, imputeTestbench, inTextSummaryTable, intRinsic, intensity.analysis, iprior, iriR, irtplay, ivmodel, kaos, kehra, kernelPhil, laketemps, lans2r, lavaSearch2, ldatuning, lddmm, likert, lipidomeR, lolog, loose.rock, lsbclust, lsl, mFD, mandelbrot, manhplot, mapStats, mappoly, marmap, matricks, mbsts, mcMST, mcb, mcvis, mdapack, mdpeer, meaRtools, medicalrisk, metaprotr, microSTASIS, microeco, microsamplingDesign, mipplot, mizer, mlergm, modnets, morse, mortAAR, motifr, mplot, mrfDepth, mudfold, multifear, multivar, mvdalab, myTAI, nandb, ncappc, neotoma, netcom, netgsa, networkreporting, networktools, networktree, nonmem2R, oaxaca, obAnalytics, omu, onemap, optiSel, ordinalLBM, otuSummary, outreg, pRF, packDAMipd, pagoo, panelvar, patPRO, patientProfilesVis, pcFactorStan, pdfetch, phase1PRMD, phylosamp, pinbasic, pingers, pixiedust, pksensi, planar, plsgenomics, plsr, polypoly, polyqtlR, pomp, pompom, pould, powerbydesign, pqantimalarials, predict3d, prepdat, primerTree, promotionImpact, proteomics, psData, pscore, pspline.inference, ptycho, puzzle, qdap, qgraph, quadrupen, quantable, quantkriging, rADA, rKOMICS, rSQM, rWBclimate, rYoutheria, rabhit, randomForestExplainer, rbi, rbi.helpers, rdiversity, refund.shiny, rlfsm, rmcfs, rmoo, rnmamod, robCompositions, romic, rplos, rsbp, rusk, rwty, sValues, santaR, saotd, sbm, scCATCH, scITD, scRNAtools, scorecardModelUtils, sctransform, segclust2d, sharpshootR, shinyKGode, shinystan, signed.backbones, siland, simmr, simrel, simulariatools, singleCellHaystack, snht, soc.ca, sorvi, soundgen, sourceR, sparsevar, speaq, spectacles, spiR, sprm, stability, staggered, statVisual, statgenHTP, svars, sysid, taRifx, tashu, telefit, testarguments, testcorr, tetraclasse, timma, tldr, traitdataform, treeDA, tsentiment, tsiR, tvm, updog, valse, vanddraabe, veccompare, viewpoly, visa, vmd, wTO, warpMix, weaana, wevid, widyr, wpa, wppExplorer, wql, xsp, xxIRT, yaps, yorkr, zebu, zonator.

Depended on by AFheritability, AurieLSHGaussian, BCellMA, DIMORA, MicroNiche, ScottKnottESD, SpatialFloor, TriMatch, clickstream, diffeR, diverse, eirm, gapmap, ifaTools, infinitefactor, interlineaR, mhtboot, morph, pgsc, pxR, seawaveQ, tmpm, toolmaRk, validateRS, wordmatch.

Suggested by ALUES, ARPobservation, AdaptGauss, CGGP, ChemoSpecUtils, DeclareDesign, DirectEffects, ENMTools, FCPS, GeneralizedUmatrix, IncDTW, Information, Lahman, MGLM, MOEADr, MSEtool, MTLR, MTPS, Markovchart, MoMPCA, MortalityTables, MultiATSM, NitrogenUptake2016, OpenMx, PDQutils, ParamHelpers, Perc, ProjectionBasedClustering, RDML, RGENERATEPREC, RaJIVE, Rlda, Rnvd3, SACOBRA, SAMtool, SDMtune, SFSI, SightabilityModel, SongEvo, Tmisc, adept, admix, agridat, aldvmm, alluvial, analyzer, bmlm, bmscstan, bodenmiller, bridgedist, bsem, causaldrf, classmap, clinDataReview, codyn, colorBlindness, comparer, countfitteR, cytofan, dartR, datplot, doMIsaul, dominanceanalysis, eiCompare, epca, fddm, firebehavioR, fitHeavyTail, flowr, frequencyConnectedness, funData, germinationmetrics, ggQC, ggalt, ggforce, ggsci, ggswissmaps, ghcm, glmmTMB, gpbStat, hdf5r, heplots, heuristica, hilbertSimilarity, httk, ibawds, iheatmapr, irtrees, kergp, knitrBootstrap, lda, logitnorm, ltbayes, magclass, matrixStrucTest, metR, metafolio, metamicrobiomeR, mgc, miRetrieve, microplot, mlrMBO, mlxR, mmpf, mosaicData, mutSignatures, nCov2019, nLTT, nc, neurobase, nlmixr, nser, nullabor, oRus, opticskxi, pals, pdSpecEst, penppml, phenofit, polymapR, popEpi, primer, productplots, propr, psd, qad, rAmCharts4, ragtop, rayshader, rbiom, refund, rfordummies, robustbase, robustlmm, rpf, rrscale, rtop, sdmpredictors, sensitivity, shadow, snpReady, socialmixr, spNetwork, sparklyr, spatialwarnings, ssdtools, stepgbm, steprf, streamDepletr, superb, swag, tableone, tictactoe, tidytext, tracerer, treecm, treespace, tukeytrend, vcfR, vkR.

See at CRAN