0

I have a large data frame of testing values over numerous sessions and I would like to rearrange the structure of it based off of the session number.

How can I "transform" a data frame from this...

reupload

to this...?

enter image description here

EDIT: Here is the code that sovled the issue...

library(tidyverse)
df2 <- df %>% 
  pivot_wider(names_from = session,
    values_from=c(weight, active, inactive, reward, beam_breaks))
jc2525
  • 141
  • 10

1 Answers1

0

As suggested in comments you have to reshape your data. The data you showed looks in long format so you will have to transform to wide format. Here the code for an output which is closer to what you want using tidyverse functions and dummy data:

library(tidyverse)
#Data
df <- structure(list(fr = c(1, 1, 1, 1, 1, 1), session = c(1L, 1L, 
1L, 2L, 2L, 2L), subject = c(1L, 2L, 3L, 1L, 2L, 3L), group = structure(c(1L, 
1L, 2L, 1L, 1L, 2L), .Label = c("heroin", "saline"), class = "factor"), 
    boxnum = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("Box1", 
    "Box2", "Box3"), class = "factor"), weight = c(268, 265, 
    255, 260, 221, 244), active = c(104, 58, 67, 59, 52, 75), 
    inactive = c(15, 15, 11, 11, 12, 16), reward = c(25, 37, 
    20, 28, 36, 22), beam_breaks = c(499265, 459925, 451156, 
    520617, 536350, 478565)), class = "data.frame", row.names = c(NA, 
-6L))

Now, we reshape to wide:

#Code
df2 <- df %>% pivot_wider(names_from = session,
                   values_from=c(weight,active,inactive,reward,beam_breaks))

Output:

# A tibble: 3 x 14
     fr subject group boxnum weight_1 weight_2 active_1 active_2 inactive_1 inactive_2 reward_1
  <dbl>   <int> <fct> <fct>     <dbl>    <dbl>    <dbl>    <dbl>      <dbl>      <dbl>    <dbl>
1     1       1 hero~ Box1        268      260      104       59         15         11       25
2     1       2 hero~ Box2        265      221       58       52         15         12       37
3     1       3 sali~ Box3        255      244       67       75         11         16       20
# ... with 3 more variables: reward_2 <dbl>, beam_breaks_1 <dbl>, beam_breaks_2 <dbl>
Duck
  • 39,058
  • 13
  • 42
  • 84