0

I have a data frame like this

test <- data.frame(matrix(nrow = 18, ncol = 3))
colnames(test) <- c("subject","session","f1")
test$subject <- c(1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3)
test$session <- c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2)
test$f1 <-      c(29,52,72,42,50,52,30,49,63,51,37,43,1,3,2,1,2,0)

I would like it to look like this

test <- data.frame(matrix(nrow=6,ncol = 5))
colnames(test) <- c("subject","session","t1","t2","t3")
test$subject <- c(1,2,3,1,2,3)
test$session <- c(1,1,1,2,2,2)
test$t1 <- c(29,42,30,51,1,1)
test$t2 <- c(52,50,49,37,3,2)
test$t3 <- c(72,52,63,43,2,0)

How would I go about changing it?

jc2525
  • 141
  • 10

1 Answers1

2

We could use just pivot_wider() with names_prefix() argument: as proposed by @Martin Gal without unnest:

library(tidyr)
library(dplyr)

test %>% 
  mutate(rn = row_number(), .by = c(subject, session)) %>% 
  pivot_wider(names_from = "rn", 
              values_from = "f1",  
              names_prefix = "t_")
library(tidyr)
library(dplyr)

test %>%
  mutate(row = row_number(), .by = c(subject, session)) %>% 
  pivot_wider(names_from = row, values_from = f1, 
              names_prefix = "t", names_sort = TRUE, 
              values_fn = list) %>% 
  unnest(cols = starts_with("t"))

  subject session t1 t2 t3
1       1       1 29 52 72
2       2       1 42 50 52
3       3       1 30 49 63
4       1       2 51 37 43
5       2       2  1  3  2
6       3       2  1  2  0
TarJae
  • 72,363
  • 6
  • 19
  • 66
  • I get an error with this...Error in `pivot_longer()`: ! `cols` must select at least one column. – jc2525 Apr 10 '23 at 19:06
  • Error in `pivot_longer()`: ! Can't subset columns that don't exist. ✖ Column `t1` doesn't exist. – jc2525 Apr 10 '23 at 19:10
  • 1
    Or without nesting: `test %>% mutate(rn = row_number(), .by = c(subject, session)) %>% pivot_wider(names_from = "rn", values_from = "f1", names_prefix = "t_")` – Martin Gal Apr 10 '23 at 19:16
  • Error in `n()`: ! Must only be used inside data-masking verbs like `mutate()`, `filter()`, and `group_by()`. – jc2525 Apr 10 '23 at 19:38
  • you need dplyr >= 1.1.0 – TarJae Apr 10 '23 at 19:40
  • 1
    It worked. I realized there was a package that needed to be detached in order for the code to work. Thank you – jc2525 Apr 11 '23 at 14:43