Reshape data frame to convert factors into columns in R

Posted by Alexander L. Belikoff on Stack Overflow See other posts from Stack Overflow or by Alexander L. Belikoff
Published on 2010-03-08T19:27:38Z Indexed on 2010/03/08 19:36 UTC
Read the original article Hit count: 400

Filed under:
|
|

I have a data frame where one particular column has a set of specific values (let's say, 1, 2, ..., 23). What I would like to do is to convert from this layout to the one, where the frame would have extra 23 (in this case) columns, each one representing one of the factor values. The data in these columns would be booleans indicating whether a particular row had a given factor value... To show a specific example:

Source frame:

ID       DATE         SECTOR
123      2008-01-01   1
456      2008-01-01   3
789      2008-01-02   5
... <more records with SECTOR values from 1 to 5>

Desired format:

ID       DATE         SECTOR.1   SECTOR.2   SECTOR.3   SECTOR.4   SECTOR.5
123      2008-01-01      T          F          F          F          F
456      2008-01-01      F          F          T          F          F
789      2008-01-02      F          F          F          F          T

I have no problem doing it in a loop but I hoped there would be a better way. So far reshape() didn't yield the desired result. Help would be much appreciated.

© Stack Overflow or respective owner

Related posts about r

    Related posts about reshape