There's a few ways to do this but here's one way:
library(tidyverse)
input_data = tribble(
~"id", ~"name", ~"surname", ~"date_test", ~"result_test",
1 , "franck" , "wilson" , "01-2002" , "P",
1 , "franck" , "wilson" , "07-2004" , "N",
1 , "franck" , "wilson" , "04-2008" , "N",
2 , "annie", "mark", "08-2001" , "N",
2 , "annie", "mark", "03-2005" , "P"
)
intermediate_data = input_data %>%
# add a counter for the tests performed
group_by(id, name, surname) %>%
mutate(test_rep = row_number())
maxTest <- pull(intermediate_data, test_rep) %>% max()
output_data <- intermediate_data %>%
pivot_longer(cols = c(date_test, result_test),
names_to = "variable",
values_to = "readout") %>%
pivot_wider(id_cols = c(id, name, surname),
names_from = c(variable, test_rep),
names_sep = "_",
values_from = readout)
maxTest
#> [1] 3
output_data
#> # A tibble: 2 x 9
#> # Groups: id, name, surname [2]
#> id name surname date_test_1 result_test_1 date_test_2 result_test_2
#> <dbl> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 1 franck wilson 01-2002 P 07-2004 N
#> 2 2 annie mark 08-2001 N 03-2005 P
#> # ... with 2 more variables: date_test_3 <chr>, result_test_3 <chr>
Created on 2022-04-05 by the reprex package (v2.0.1)