Graphics Reference
In-Depth Information
See Also
See Converting Data from Long to Wide to do conversions in the other direction, from long to
wide.
See the stack() function for another way of converting from wide to long.
Converting Data from Long to Wide
Problem
You want to convert a data frame from “long” format to “wide” format.
Solution
Use the dcast() function from the reshape2 package. In this example, we'll use the plum data
set, which is in a long format:
library(gcookbook) # For the data set
plum
length time survival count
long at_once dead 84
long in_spring dead 156
short at_once dead 133
short in_spring dead 209
long at_once alive 156
long in_spring alive 84
short at_once alive 107
short in_spring alive 31
The conversion to wide format takes each unique value in one column and uses those values
as headers for new columns, then uses another column for source values. For example, we can
“move” values in the survival column to the top and fill them with values from count :
library(reshape2)
dcast(plum, length + time ~ survival, value.var = "count" )
length time dead alive
long at_once
84
156
long in_spring 156
84
short at_once 133
107
short in_spring 209
31
Search WWH ::




Custom Search