1

I have a dataframe which looks similarly to this one

  ID  Members  Gender    Age

  1     2       1        35
  1     2       2        33
  2     3       1        54
  2     3       2        50
  2     3       1        15
  3     1       1        65

I want to transform it in this way

  ID  Members  Gender_1 Gender_2 Gender_3    Age_1 Age_2 Age_3

  1    2         1        2       NA          35    33    NA
  2    3         1        2       1           54    50    15
  3    1         1        NA      NA          65    NA    NA

I tried using

answer2<-data.table::dcast(df, ID ~ Members, value.var=c("Gender","Age"))

following this thread Reshape multiple value columns to wide format, but I still get the same error

Error in .subset2(x, i, exact = exact) : recursive indexing failed at level 2 In addition: Warning message: In if (!(value.var %in% names(data))) { : the condition has length > 1 and only the first element will be used

Could please anyone help me? Many thanks

Marco Mello
  • 175
  • 1
  • 9
  • 1
    you need to convert your data to data.table first. Try `library(data.table) ; setDT(df) ; dcast(df, ID ~ Members, value.var=c("Gender","Age"))` – David Arenburg Aug 30 '18 at 17:49
  • 3
    Broadly speaking, I'm not sure this is a good idea, as it will be easier to work with this data in long form. If there's some significance to the row order, add it as a variable. – alistaire Aug 30 '18 at 17:51
  • Thank you so much for your help!!! It works. – Marco Mello Aug 30 '18 at 17:55

0 Answers0