r - 如何正确组合 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
解决方案
我们可以用cSplit
library(splitstackshape)
cSplit(df, "strings", "_", drop = FALSE)
或使用separate
fromtidyr
library(tidyr)
library(stringr)
df %>%
separate(strings, into = str_c('string_', 1:3), remove = FALSE)
推荐阅读
- django - django 错误:ModuleNotFoundError 没有名为“siteerrors”的模块
- python - 有没有办法参数化 VS Code 的 python.pythonPath 设置?
- javascript - 无法在 Visual Studio 中调试 JS:验证断点位置
- python - Python Lambda 函数变量排序
- javascript - 有什么办法可以将一个java脚本字符串变成一个数组然后改变数组值然后最后把它变成一个字符串
- c# - 为什么我的列表框中没有显示任何内容?C#
- c# - ASP.Net Azure OpenId 集成
- android - Android - 填充回收站视图问题
- java - Java多线程在长进程中减慢,最大CPU使用率
- xamarin.forms - Xamarin.Forms - 信息丰富的应用布局建议/方向