首页 > 解决方案 > 如何正确组合 mutate 和 str_match?

问题描述

假设我想将一个字符串列拆分为单独的列。为此,我使用了 stringr 包中的 mutate 和 str_match(或 str_replace),但结果并不理想。

设置数据框并拆分列:

df <-
  data.frame(strings = c('a_b_c', 'ab_cd_ef', 'abc_def_ghi')) %>%
  mutate(string = stringr::str_match(strings, '([a-z]+)_([a-z]+)_([a-z]+)')) 

df
      strings    string.1 string.2 string.3 string.4
1       a_b_c       a_b_c        a        b        c
2    ab_cd_ef    ab_cd_ef       ab       cd       ef
3 abc_def_ghi abc_def_ghi      abc      def      ghi

在查看列名时,我只看到两列。这也使得引用列变得复杂。我认为它与 str_match 函数输出的矩阵格式有关。

df %>% ncol
[1] 2

df %>% colnames
[1] "strings" "string"

有没有一种简单的方法可以让这些新列表现得像普通的 data.frame 列?如果可能,使用重命名步骤。这是我想要的东西:

df %>% ncol
[1] 5

df %>% colnames
[1] "strings" "string_1" "string_2" "string_3" "string_4"

df
      strings    string_1 string_2 string_3 string_4
1       a_b_c       a_b_c        a        b        c
2    ab_cd_ef    ab_cd_ef       ab       cd       ef
3 abc_def_ghi abc_def_ghi      abc      def      ghi

标签: rstringrdplyr

解决方案


我们可以用cSplit

library(splitstackshape)
cSplit(df, "strings", "_", drop = FALSE)

或使用separatefromtidyr

library(tidyr)
library(stringr)
df %>%
    separate(strings, into = str_c('string_', 1:3), remove = FALSE)

推荐阅读