2

I'm so confused here. I have a dataset that looks like this:

dataset <- data.frame(
  Label = c(1.1,1.1,1.1,2.1,2.1,2.1,3.1,3.1,3.1,1.6,1.6,1.6,2.6,2.6,2.6,3.6,3.6,3.6),
  StudyID = c(1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3),
  ScanNumber = c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3),
  Timepoint = c(1,1,1,1,1,1,1,1,1,6,6,6,6,6,6,6,6,6),
  Fat = c(3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8),
  Lean = c(5,5,5,6,6,6,7,7,7,3,3,3,4,4,4,5,5,5)
)

I want to pivot_wider so that I have triplicate Fat and Lean measurements for each StudyID and Timepoint. You can see the Label contains information on the StudyID and Timepoint combined (for example, say StudyID = 1 and Timepoint = 6, Label is 1.6). This is how I am doing it:

newdataset <- dataset %>%
  pivot_wider(
    id_cols = Label,
    names_from = ScanNumber,
    names_sep = "_",
    values_from = c(Fat, Lean)
  )

However, the output I get no longer includes StudyID and Timepoint. I require these variables to then merge the dataset with another dataset. I have been searching the internet but can't seem to find how to keep StudyID and Timepoint in the new dataset after performing pivot_wider. What am I missing?

Thanks in advance.

r2evans
  • 141,215
  • 6
  • 77
  • 149
Dr Wampa
  • 443
  • 3
  • 8
  • 1
    FYI - `id_cols` defaults to all the fields in the df you don't explicitly reference. So `dataset %>% pivot_wider(names_from = ScanNumber,names_sep = "_", values_from = c(Fat, Lean))` is all you need – Mitchell Graham Jul 30 '20 at 21:01

1 Answers1

2

Combine them within id_cols, which are preserved (and grouped):

dataset %>%
  pivot_wider(
    id_cols = c(Label, StudyID, Timepoint),
    names_from = ScanNumber,
    names_sep = "_",
    values_from = c(Fat, Lean)
  )
# # A tibble: 6 x 9
#   Label StudyID Timepoint Fat_1 Fat_2 Fat_3 Lean_1 Lean_2 Lean_3
#   <dbl>   <dbl>     <dbl> <dbl> <dbl> <dbl>  <dbl>  <dbl>  <dbl>
# 1   1.1       1         1     3     3     3      5      5      5
# 2   2.1       2         1     4     4     4      6      6      6
# 3   3.1       3         1     5     5     5      7      7      7
# 4   1.6       1         6     6     6     6      3      3      3
# 5   2.6       2         6     7     7     7      4      4      4
# 6   3.6       3         6     8     8     8      5      5      5
r2evans
  • 141,215
  • 6
  • 77
  • 149