1

How can I transform a dataset in "wide" format that has sets of columns of different types, into "long" format, as in the example bellow? Preferably using tidyr (and dplyr, etc) or some equally simple syntax.

d_wide <- data.frame(
             pair_id=1:3,
             name_wife=c('Ana','Maria','Kely'),blood_type_wife=c('A','B','C'), age_wife=c(34,21,55),
             name_husb=c('Bob','Peter','John'),blood_type_husb=c('B','O','A'), age_husb=c(31,24,60)
          )

d_long <- data.frame(
             pair_id=c(1,1,2,2,3,3),
             role=c('wife','husb','wife','husb','wife','husb'),
             name=c('Ana','Bob','Maria','Peter','Kely','John'),
             blood=c('A','B','B','O','C','A'), 
             age=c(34,31,21,24,55,60)
          ) 

OBS: other related SO questions, such as this, involve sets of columns of the same type, all numeric. Then the answer in those involves gathering (melting) the data into a "ultra-long" format and spreading back to the desired long format. This would not work here, as the variables are of different types, so they can´t be represented by the same "value" column in the ultra-long format.

Community
  • 1
  • 1
LucasMation
  • 1,886
  • 2
  • 15
  • 38
  • 1
    Short answer, from the linked dupe, is that you're going to be better off with `melt` from "data.table" as opposed to `melt` from "reshape2". – A5C1D2H2I1M1N2O1R2T1 Mar 21 '16 at 14:03
  • Also, I presume that `name_wife=c('Bob','Peter','John')` should have been `name_husb(...)`. – A5C1D2H2I1M1N2O1R2T1 Mar 21 '16 at 14:04
  • Tks a lot! I just corrected the name_husb mistake. O whether this is a duplicate: although I agree the answer will be the same, the other question is framed focussing on the variable names (if their suffix is numeric or character). The point is the difference in the types of information the variables contain. Thus, keeping this as a separate question may be useful. – LucasMation Mar 21 '16 at 14:18
  • 1
    Dupes are just pointers. They don't delete the question. The point about conversion of data types using `gather` is covered in [this answer](http://stackoverflow.com/a/34427860/1270695) (at the same question) in the first list. – A5C1D2H2I1M1N2O1R2T1 Mar 21 '16 at 14:20

0 Answers0