2

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!

jyu1992
  • 25
  • 4
  • What is the problem with the `melt`. It gives three columns, right?. If you need Hectares column, `transform(m, Hectares = Acres*2.47)` – akrun Nov 25 '15 at 06:31
  • The melt function actually worked. I had 3 columns. When I used the transform function, it showed the results in the console, but in the data table, a hectare column wasn't added – jyu1992 Nov 25 '15 at 18:23
  • You need to assign it i.e. `m <- transform(m, Hectares= Acres/2.47)` But more simple way would be `m$Hectares <- m$Acres/2.47` – akrun Nov 25 '15 at 18:25
  • omg, yes I get it now. Thanks that makes a lot of sense! – jyu1992 Nov 25 '15 at 18:34

2 Answers2

2

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][]
akrun
  • 874,273
  • 37
  • 540
  • 662
1

I find tidyr easier

library(dplyr)
library(tidyr)

data %>%
  gather(Year, Acres, -State) %>%
  mutate(Hectares = Acres * 2.47)
bramtayl
  • 4,004
  • 2
  • 11
  • 18