首页 > 解决方案 > 如何使用 dummy_cols 拆分列

问题描述

我在 R 中使用fastDummies并尝试使用该split参数。我没有让它正确分裂。这就是我正在尝试的。

library(fastDummies)

ID <- seq(1:4)
pets <- c("dog", "cat;dog;mouse", "dog;mouse", "cat")
df <- data.frame("ID" = ID, "pets" = pets, stringsAsFactors = FALSE)

dummyTest <- dummy_cols(df, select_columns = c("pets"), remove_first_dummy = FALSE,
                        remove_most_frequent_dummy = FALSE, sort_columns = FALSE,
                        ignore_na = FALSE, split = ";")

print(dummyTest)

# ID          pets pets_dog pets_cat;dog;mouse pets_dog;mouse pets_cat
# 1  1           dog        1                  0              0        0
# 2  2 cat;dog;mouse        1                  1              0        1
# 3  3     dog;mouse        1                  0              1        0
# 4  4           cat        0                  0              0        1

请注意,它正确地找到了“dog”和“cat”,但没有找到“mouse”。是因为“鼠标”本身并不作为“宠物”的价值存在吗?我想得到这个结果:

  ID          pets pets_dog pets_cat pets_mouse
1  1           dog        1        0          0
2  2 cat;dog;mouse        1        1          1
3  3     dog;mouse        1        0          1
4  4           cat        0        1          0

我的错误是什么?

标签: rcategorical-datadummy-variable

解决方案


推荐阅读