两个条件下的部分组数据框

Partial group dataframe by two conditions

假设我有以下数据框,其中有 3 列(颜色(黄色、绿色或红色)、标签(A、B 或 C)和 val(数值))。

每种颜色有 100 个条目。这会产生一个 3 x 900 的数据框。

col label val
yellow1 A 23
yellow1 B 2
yellow1 C 12
green1 A 42
green1 B 55
green1 C 21
yellow2 A 33
yellow2 B 56
yellow2 C 45

如何更改此数据框,使每种颜色和标签都有一个单独的列。例如...

Yellow.A Yellow.B Yellow.C Green.A Green.B Green.C Red.A
23 2 12 42 55 21 64
33 56 45 24 52 42 24
23 2 232 53 32 24 112

注意:我不想为 Yellow1.A、Yellow2.A...等单独列。 'Yellow' 的所有“A”都应该在一个列中。

我使用 dyplr/tidyverse 以及基础。

基础 R

dat$col <- sub("[0-9]+$", "", dat$col)
tmp <- lapply(split(dat, dat[c("col", "label")]), `[[`, "val")
tmp <- lapply(tmp, `length<-`, max(lengths(tmp)))
as.data.frame(tmp)
#   green.A yellow.A green.B yellow.B green.C yellow.C
# 1      42       23      55        2      21       12
# 2      NA       33      NA       56      NA       45

数据

dat <- structure(list(col = c("yellow1", "yellow1", "yellow1", "green1", "green1", "green1", "yellow2", "yellow2", "yellow2"), label = c("A", "B", "C", "A", "B", "C", "A", "B", "C"), val = c(23L, 2L, 12L, 42L, 55L, 21L, 33L, 56L, 45L)), class = "data.frame", row.names = c(NA, -9L))