分离并创建虚拟变量列
separate and create dummy variable columns
我有一些这种格式的数据:
#> # A tibble: 3 × 2
#> item colors
#> <int> <chr>
#> 1 1 blue
#> 2 2 blue / pink / red
#> 3 3 pink / white
我想要的输出是:
#> # A tibble: 3 × 5
#> item blue pink red white
#> <int> <int> <int> <int> <int>
#> 1 1 1 0 0 0
#> 2 2 1 1 1 0
#> 3 3 0 1 0 1
在 tidyverse 中,有没有简单的方法来做到这一点?
如果有帮助,我确实有颜色的 df,例如。
df_colors
#> # A tibble: 4 × 1
#> color
#> <chr>
#> 1 blue
#> 2 pink
#> 3 red
#> 4 white
我正在使用的真实示例有多种颜色。
数据输入代码如下:
library(tidyverse)
df <- tibble::tribble(
~item, ~colors,
1L, "blue",
2L, "blue / pink / red",
3L, "pink / white"
)
df
library(tidyverse)
df_desired <- tibble::tribble(
~item, ~blue, ~pink, ~red, ~white,
1L, 1L, 0L, 0L, 0L,
2L, 1L, 1L, 1L, 0L,
3L, 0L, 1L, 0L, 1L
)
df_desired
df_colors <- tibble::tribble(
~color,
"blue",
"pink",
"red",
"white"
)
df_colors
您可以先 separate_rows
然后 pivot_wider
:
library(dplyr)
library(tidyr)
df %>%
# create row ID:
mutate(row = row_number()) %>%
# separate rows on " /":
separate_rows(colors, sep = ' /') %>%
# pivot dataframe wider:
pivot_wider(names_from = colors, values_from = colors,
values_fn = function(x) 1, values_fill = 0) %>%
# deselect obsolete column:
select(-row)
# A tibble: 3 x 6
item blue ` pink` ` red` pink ` white`
<int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1 0 0 0 0
2 2 1 1 1 0 0
3 3 0 0 0 1 1
我有一些这种格式的数据:
#> # A tibble: 3 × 2
#> item colors
#> <int> <chr>
#> 1 1 blue
#> 2 2 blue / pink / red
#> 3 3 pink / white
我想要的输出是:
#> # A tibble: 3 × 5
#> item blue pink red white
#> <int> <int> <int> <int> <int>
#> 1 1 1 0 0 0
#> 2 2 1 1 1 0
#> 3 3 0 1 0 1
在 tidyverse 中,有没有简单的方法来做到这一点?
如果有帮助,我确实有颜色的 df,例如。
df_colors
#> # A tibble: 4 × 1
#> color
#> <chr>
#> 1 blue
#> 2 pink
#> 3 red
#> 4 white
我正在使用的真实示例有多种颜色。
数据输入代码如下:
library(tidyverse)
df <- tibble::tribble(
~item, ~colors,
1L, "blue",
2L, "blue / pink / red",
3L, "pink / white"
)
df
library(tidyverse)
df_desired <- tibble::tribble(
~item, ~blue, ~pink, ~red, ~white,
1L, 1L, 0L, 0L, 0L,
2L, 1L, 1L, 1L, 0L,
3L, 0L, 1L, 0L, 1L
)
df_desired
df_colors <- tibble::tribble(
~color,
"blue",
"pink",
"red",
"white"
)
df_colors
您可以先 separate_rows
然后 pivot_wider
:
library(dplyr)
library(tidyr)
df %>%
# create row ID:
mutate(row = row_number()) %>%
# separate rows on " /":
separate_rows(colors, sep = ' /') %>%
# pivot dataframe wider:
pivot_wider(names_from = colors, values_from = colors,
values_fn = function(x) 1, values_fill = 0) %>%
# deselect obsolete column:
select(-row)
# A tibble: 3 x 6
item blue ` pink` ` red` pink ` white`
<int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1 0 0 0 0
2 2 1 1 1 0 0
3 3 0 0 0 1 1