Martin Martin - 3 months ago 13
R Question

How can I insert actual values in dataframe as columns in R?

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.

Answer

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