Reshape: Reshape data

ReshapeR Documentation

Reshape data

Description

Convenience wrappers for reshape where direction is "long" (melt) or "wide" (cast).

Usage

cast(
  data,
  idvar = list(1),
  timevar = list(2),
  v.names = list(3:ncol(data)),
  ...
)

melt(data, varying = list(1:ncol(data)), ...)

Arguments

data

a data frame

idvar

id variable(s)

timevar

time point variable(s)

v.names

long variable(s) to be flattened

...

additional arguments passed to reshape

varying

variable(s) to melt into column(s)

Details

These functions set defaults for reshaping data; any defaults may be overwritten by simply passing arguments to ... (names must match exactly and no partial matching is allowed or they will be ignored).

By default, cast assumes data is a data frame with at least three columns representing id, time point, and value variables (any additional columns will be considered value variables as well). melt by default assumes no id variables and will melt all columns.

idvar, timevar, v.names, and varying can be passed as a vector of column indices or character strings of variable names or as a list of indices or character strings names for convenience.

Value

The reshaped data frame with added attributes to simplify reshaping back to the original form.

See Also

reshape

Examples

## default of melt is no id variable so all are melted
melt(mtcars)

## compare to
reshape(mtcars, dir = 'long', varying = list(names(mtcars)))


dat <- data.frame(id = rep(1:4, rep(2, 4)),
                  visit = I(rep(c('Before', 'After'), 4)),
                  x = abs(rpois(4, 10)), y = -runif(4))

## equivalent ways to give `varying`
melt(dat, list(3:4))
melt(dat, 3:4)
l <- melt(dat, c('x','y'))

## equivalent ways to give `idvar`, `timevar`, `v.names`
cast(l, c('id','visit'), 'variable', 'value')
cast(l, list('id','visit'), 3, 4)
cast(l, 1:2, 3, list('value'))

## cast assumes columns are id, time, followed by all varying:
cast(dat)


dat <- within(dat, {
  xx <- abs(rpois(4, 10))
  yy <- -runif(4, 1, 2)
})

## melting multiple variables simultaneously
melt(dat, list(c(3,6), c(4:5)))

## note that a vector cannot be used here for the same results
melt(dat, c('x','xx','y','yy'))

## use a list instead
melt(dat, list(c('x','xx'), c('y','yy')))


## melt or cast can also be undone as other reshape objects
w1 <- reshape(Indometh, v.names = "conc", idvar = "Subject",
              timevar = "time", direction = "wide", new.row.names = 1:6)
w2 <- cast(Indometh, v.names = "conc", idvar = "Subject",
           timevar = "time", direction = "wide")

identical(w1, w2) ## TRUE
identical(reshape(w1), reshape(w2)) ## TRUE


raredd/rawr documentation built on March 4, 2024, 1:36 a.m.