0

can anyone please help me out with the R melt function for reshaping the data. I am trying to convert the df from long to wide, but when I do, I loose most of my data while reshaping.

input data

dd <- data.frame(
  Time.point = c(4L, 4L, 2L, 6L, 4L, 4L, 6L, 6L, 6L, 4L),
  CellType = c("IG2", "proNeu-2", "Multi-Lin-1", "DC", 
              "MP", "Eosinophils", "IG2", "cMoP", "preNeu-1", "proNeu-2"), 
  CloneID = c("cl", "cl", "cl", "cl1", "cl1", "cl1", "cl10", 
              "cl10", "cl10", "cl10")
)
#    Time.point    CellType CloneID
# 1           4         IG2      cl
# 2           4    proNeu-2      cl
# 3           2 Multi-Lin-1      cl
# 4           6          DC     cl1
# 5           4          MP     cl1
# 6           4 Eosinophils     cl1
# 7           6         IG2    cl10
# 8           6        cMoP    cl10
# 9           6    preNeu-1    cl10
# 10          4    proNeu-2    cl10

expected result

desired <- data.frame(
  CloneID = c("cl", "cl1"), 
  Timepoint2 = c("Multi-Lin-1", "Eosinophils|MP"), 
  Timepoint4 = c("IG2|proNeu-2", NA), 
  Timepoint6 = c(NA, "DC")
)
 
#   CloneID     Timepoint2   Timepoint4 Timepoint6
# 1      cl    Multi-Lin-1 IG2|proNeu-2       <NA>
# 2     cl1 Eosinophils|MP         <NA>         DC

code which I used

nt = reshape(data=nt,idvar="CloneID",
                   v.names = "CellType",
                   timevar = "Time.point",
                   direction="wide")```

Error : Warning messages:
1: In reshapeWide(data, idvar = idvar, timevar = timevar, varying = varying,  :
  multiple rows match for Time.point=4: first taken
2: In reshapeWide(data, idvar = idvar, timevar = timevar, varying = varying,  :
  multiple rows match for Time.point=2: first taken
3: In reshapeWide(data, idvar = idvar, timevar = timevar, varying = varying,  :
  multiple rows match for Time.point=6: first taken

MrFlick
  • 195,160
  • 17
  • 277
  • 295
newbe
  • 1
  • 2
  • 1
    please include your data and desired output as cop/pastable code rather than images. You can use `dput()` and add the output to your question. Also add the code you have tried and the errors you are getting – morgan121 Aug 19 '20 at 03:54
  • Make sure to actually show the code you tried. The existing answer should work. You should make it clear how your question is different if that's not the case. – MrFlick Aug 19 '20 at 04:01
  • I tried al other existing answers related to similar post. it gives same error – newbe Aug 19 '20 at 04:12
  • I'd just use `tidyr` rather than `reshape`. For example: `dd %>% tidyr::pivot_wider(id_cols=CloneID, names_from=Time.point, values_from=CellType, names_glue="Timepoint{Time.point}", values_fn = function(x) paste(x, collapse="|"))` – MrFlick Aug 19 '20 at 04:49

0 Answers0