From a long to a wide R data frame, with array values

From a “long” data frame with columns containing the names of measured properties and corresponding vectors of values, attempting to make a “wide” data frame with a column for each measured property. Appears as though the cast() function of the reshape package should do this, but I can only get it to return the lengths of the vectors of measured values without giving me an error. Realized I can do this with R’s base functionality:

Starting with a data frame named “crabs”…

> crabs
   loc aphia_id    var        val
1 a123       43  abund          3
2 a123       43 cwidth    1, 6, 3
3   b1       43  abund          4
4   b1       43 cwidth 4, 3, 2, 5
5 a123      456  abund          1
6 a123      456 cwidth          4
7 a123      203  abund          1
8 a123      203 cwidth          3

> abund <- crabs[crabs$var==”abund”,] > abund$abund <- abund$val > abund$val <- NULL > abund$var <- NULL > cw <- crabs[crabs$var==”cwidth”,] > cw$cwidth <- cw$val > cw$val <- NULL > cw$var <- NULL > crabs.wide <- merge(abund,cw,by=c(“loc”,”aphia_id”),all.x=T,all.y=T) > crabs.wide
   loc aphia_id abund     cwidth
1 a123      203    1             3
2 a123       43     3      1, 6, 3
3 a123      456    1             4
4   b1       43      4   4, 3, 2, 5
>

Note: R is using an attractive but misleading display for crabs and crabs.wide here when called from the prompt by name. The cwidth column is shown with comma-separated values. Use of the str() function verifies that they are indeed numeric vectors.

Guessing the plyr package must address this kind of reshape, as well.

Advertisements
This entry was posted in data munging, R and tagged , , , , , . Bookmark the permalink.