A tidyverse
решение, используя gather
и spread
из tidyr
pacakge:
library(dplyr)
library(tidyr) #version 1.0.0 which has pivot_wider
df1 %>%
group_by(Type) %>%
mutate(name_x = row_number()) %>%
gather(key=var, value=val, c(Score, Time)) %>%
mutate(var = paste(var, name_x, sep="_")) %>%
select(-name_x) %>%
spread(key=var, value=val)
#> # A tibble: 3 x 11
#> # Groups: Type [3]
#> id Date Type Score_1 Score_2 Score_3 Score_4 Time_1 Time_2 Time_3 Time_4
#> <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <chr> <chr> <chr> <chr>
#> 1 1 2001~ aaa 123 456 789 NA 12:12 13:12 14:12 <NA>
#> 2 2 2001~ ddd 113 145 NA NA 15:12 16:12 <NA> <NA>
#> 3 3 2001~ bbb 789 145 113 145 17:12 18:12 19:12 20:12
Вы можете сделать то же самое с pivot_wider
гораздо удобнее:
df1 %>%
group_by(Type) %>%
mutate(name_x = row_number()) %>%
pivot_wider(id_cols = c("id","Date", "Type"),
names_from = c("name_x"),
values_from = c("Score", "Time"))
Данные:
df1 <- data.frame(id=c(1,1,1,2,2,3,3,3,3),
Date = c(rep("2001-01-13", 3), rep("2001-01-16", 2), rep("2001-01-18", 4)),
Type = c(rep("aaa",3), rep("ddd", 2), rep("bbb",4)),
Score = c(123,456,789,113,145,789,145,113,145),
Time = paste0(12:20, ":12"),
stringsAsFactors = F)