jyu1992
jyu1992

Reputation: 25

Reshaping data with melt

Hi this is my sample data. The data represents a state's area harvested in acres.

State         1974   1978    1982    1987
Alabama        0      0        6      149    
Alaska         3      4        39     140
Arizona        700    200     3000   11000
Arkansas       0      10       20      30


State          Year       Acres      Hectares  
Alabama        1974         0          0
Alabama        1978         0          0
Alabama        1982         6          2.42
Alabama        1987         149        60.30

I'm trying to reshape it so it records each individual observation and includes hectares as a column too, rounded to 2 decimal places (1 hectare= 2.47 acre)

colnames(x) <-  c('state',1974,1978,1982,1987)
library(reshape2)
m <-  melt(broccoli,id='state')
colnames(m) <-  c('state','year','acres')

This is the R Code I ran, but I didn't have any luck using melt function. Any help is appreciated!

Upvotes: 2

Views: 2469

Answers (2)

akrun
akrun

Reputation: 887981

We can transform to create the Hectares column

transform(m, Hectares = Acres/2.47)

If we are using data.table

 library(data.table)
 melt(setDT(broccoli), id.var='State', variable.name='Year',
        value.name='Acres')[, Hectares := Acres/2.47][]

Upvotes: 2

bramtayl
bramtayl

Reputation: 4024

I find tidyr easier

library(dplyr)
library(tidyr)

data %>%
  gather(Year, Acres, -State) %>%
  mutate(Hectares = Acres * 2.47)

Upvotes: 1

Related Questions