我们可以使用tidyverse 方法。
- 使用
str_extract从“匹配”的每一行中提取选定的团队
- 只保留匹配的行,即用
filter 删除NA 行
- 使用
pivot_wider 在selecting 感兴趣的列之后将values_fn 重新整形为“宽” - 将values_fn 指定为length 和values_fill 为0 以将默认NA 更改为0
library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
mutate(team = str_c('Dummy_', str_extract(Matches,
regex('England|Belgium|Germany|France', ignore_case = TRUE)))) %>%
filter(complete.cases(team)) %>%
select(-Matches) %>%
pivot_wider(names_from = team, values_from = team,
values_fn = length, values_fill = 0)
-输出
# A tibble: 2 x 5
Date Dummy_England Dummy_Belgium Dummy_Germany Dummy_France
<dbl> <int> <int> <int> <int>
1 16.0 1 1 1 1
2 17.0 0 1 1 0
如果我们想在没有匹配的地方保留“日期”,请使用complete
df1 %>%
mutate(team = str_c('Dummy_', str_extract(Matches,
regex('England|Belgium|Germany|France', ignore_case = TRUE)))) %>%
filter(complete.cases(team)) %>%
select(-Matches) %>%
pivot_wider(names_from = team, values_from = team,
values_fn = length, values_fill = 0) %>%
complete(Date = unique(df1$Date), fill = list(Dummy_England = 0,
Dummy_Belgium = 0, Dummy_Germany = 0, Dummy_France = 0))
-输出
# A tibble: 3 x 5
Date Dummy_England Dummy_Belgium Dummy_Germany Dummy_France
<dbl> <dbl> <dbl> <dbl> <dbl>
1 16.0 1 1 1 1
2 17.0 0 1 1 0
3 18.0 0 0 0 0
数据
df1 <- structure(list(Date = c(16.03, 16.03, 16.03, 16.03, 16.03, 17.03,
17.03, 17.03, 17.03, 18.03, 18.03, 18.03), Matches = c("England X Brazil",
"Belgium X Argentina", "Chile X Japan", "Uruguay X Germany",
"Italy x France", "South Korea X India", "Germany X France",
"Poland X Belgium", "Colombia X Russia", "South Africa X Mexico",
"China X Japon", "Brazil X Venezuela")), class = "data.frame", row.names = c(NA,
-12L))