Вот один способ с pivot_longer
+ pivot_wider
library(dplyr)
library(tidyr)
pivot_longer(df, cols = -Participant, names_to = c("Day", "Time", "Item"),
names_pattern = "D(\\d+)_(\\d+)_(\\d+)") %>%
mutate(Item = paste0("Item",Item)) %>%
pivot_wider(names_from = Item, values_from = value)
# A tibble: 10 x 7
# Participant Day Time Item1 Item2 Item3 Item4
# <fct> <chr> <chr> <int> <int> <int> <int>
# 1 P1 1 1 6 2 3 5
# 2 P1 2 1 1 2 NA NA
# 3 P2 1 1 4 9 3 6
# 4 P2 2 1 4 1 NA NA
# 5 P3 1 1 7 4 2 8
# 6 P3 2 1 1 1 NA NA
# 7 P4 1 1 1 5 1 1
# 8 P4 2 1 6 7 NA NA
# 9 P5 1 1 2 0 8 2
#10 P5 2 1 1 4 NA NA
Мы также можем использовать extract
, используя тот же шаблон, что и names_pattern
в pivot_longer
pivot_longer(df, cols = -Participant) %>%
extract(name, into = c("Day", "Time", "Item"),
regex = "D(\\d+)_(\\d+)_(\\d+)") %>%
pivot_wider(names_from = Item, values_from = value)
данные
df <- structure(list(Participant = structure(1:5, .Label = c("P1",
"P2", "P3", "P4", "P5"), class = "factor"), D1_1_1 = c(6L, 4L,
7L, 1L, 2L), D1_1_2 = c(2L, 9L, 4L, 5L, 0L), D1_1_3 = c(3L, 3L,
2L, 1L, 8L), D1_1_4 = c(5L, 6L, 8L, 1L, 2L), D2_1_1 = c(1L, 4L,
1L, 6L, 1L), D2_1_2 = c(2L, 1L, 1L, 7L, 4L)), class = "data.frame",
row.names = c(NA, -5L))