让我们生成我们想要子集的数据框
vDates =
seq(
from = as.Date("2024-01-01"),
to = as.Date("2024-01-5"),
by = 1
)
vToy = c(1, 2, 3)
vColors = c("Blue", "Red")
tExpand = expand.grid(date = vDates, index = vToy, col = vColors)
vRemove = c(2, 5, 25)
tTable = tExpand[- vRemove, ]
rownames(tTable) = 1 : nrow(tTable)
在
2024-01-02
和 2024-01-05
上,我们没有任何 blue
类型的 1
玩具,而在 2024-01-04
上,我们没有任何 red
类型的 2
玩具。我们如何过滤表格以提取所有日期的蓝色和红色玩具并获得期望的结果tDesired
,最好使用dplyr
?
tDesired = tTable[- c(15, 18, 8), ]
在
inner_join
数据集上使用 split
的方法
library(dplyr)
library(tidyr)
splt <- split(tTable, tTable$col)
inner_join(splt$Blue, splt$Red, c("date", "index")) %>%
pivot_longer(-c(date, index), values_to="col") %>%
select(-name) %>%
arrange(col, index)
输出
# A tibble: 24 × 3
date index col
<date> <dbl> <fct>
1 2024-01-01 1 Blue
2 2024-01-03 1 Blue
3 2024-01-04 1 Blue
4 2024-01-01 2 Blue
5 2024-01-02 2 Blue
6 2024-01-03 2 Blue
7 2024-01-04 2 Blue
8 2024-01-01 3 Blue
9 2024-01-02 3 Blue
10 2024-01-03 3 Blue
11 2024-01-04 3 Blue
12 2024-01-05 3 Blue
13 2024-01-01 1 Red
14 2024-01-03 1 Red
15 2024-01-04 1 Red
16 2024-01-01 2 Red
17 2024-01-02 2 Red
18 2024-01-03 2 Red
19 2024-01-04 2 Red
20 2024-01-01 3 Red
21 2024-01-02 3 Red
22 2024-01-03 3 Red
23 2024-01-04 3 Red
24 2024-01-05 3 Red