-2

I know some basic R but I'm stuck with this dataframe handling. I need to be able to use a package or base function in R to transoform a dataframe like this.

id   value    variable 
1    25.5     max_temp
1    16.4     min_temp
2    23.1     max_temp 
3    12.1     min_temp

into this:

id   max_temp    min_temp
1     25.5        16.4
2     23.1         NA
3     NA           12.1

Check the NA example as some observations have missing measurements. Actually I can fix it directly in excel file but I'm trying to do preprocessing less manually.

Thanks.

Martin
  • 51
  • 1
  • 9

1 Answers1

2

What you want to do is to reshape the data. There are a lot of ways to do this. Here's one:

reshape(x, direction='wide', idvar='id', timevar='variable')
  id value.max_temp value.min_temp
1  1           25.5           16.4
3  2           23.1             NA
4  3             NA           12.1

reshape2::dcast has a nicer syntax:

> dcast(x, id ~ variable)
  id max_temp min_temp
1  1     25.5     16.4
2  2     23.1       NA
3  3       NA     12.1
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
  • Thanks, actually the first one worked fine for me. The second solution has inserted values as strings with the column name. – Martin Sep 01 '16 at 21:59