data.table和str_extract_all的组合

托比·索纳

我希望data.table每个分组变量中的每个数字都有一列假设我有以下数据:

Data <- data.table(Text = c("123 456", "234 567"), Group = c("A", "B"))
      Text Group
1: 123 456     A
2: 234 567     B

我想要的是:

      Text Group Number1 Number2
1: 123 456     A     123     456
2: 234 567     B     234     567

我尝试过的

Data[, c("Number1", "Number2") := str_extract_all(Text, "\\d+"), Group]

这给了我以下内容:

Error in `[.data.table`(Data, , `:=`(c("Number1", "Number2"), str_extract_all(Text,  : 
  Supplied 2 items to be assigned to group 1 of size 1 in column 'Number1'. The RHS length must either be 1 (single values are ok) or match the LHS length exactly. If you wish to 'recycle' the RHS please use rep() explicitly to make this intent clear to readers of your code.

我知道我可以使用separate,我知道我可以在每个数字/列中使用一个正则表达式,但是我想在的“一行”中找到一个聪明的解决方案str_extract_all

罗纳克·沙

我会使用cSplit,因为它是

splitstackshape::cSplit(Data, "Text", sep = " ", drop = FALSE)

但是,如果您想使用str_extract_all我们可以

Data[,paste0("number", 1:2) := purrr::transpose(stringr::str_extract_all(Text, "\\d+"))]
Data

#      Text Group number1 number2
#1: 123 456     A     123     456
#2: 234 567     B     234     567

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在gregexpr和str_extract_all函数中进行量化的交替

使用str_extract_all和unnest但从NA中丢失行

str_extract_all带十进制数字

以整洁的方式使用str_extract_all的新列

使用str_extract_all的正则表达式

str_extract_all返回不匹配的组

在 R 中为 str_extract_all 使用变量输入

组合“ by”和“ on”以加入并为data.table创建摘要列

扩展data.table以创建分组的主体和别名组合

从str_extract_all的输出中删除空字符串

我可以使用OR语句来指示Stringr的str_extract_all函数中的模式吗?

使用str_extract_all查找多个字符串

使用str_extract_all仅提取R中的前两个单词?

为什么`str_extract_all`对于不匹配项返回NA?

str_extract_all返回一个列表,但我想要一个向量

R中的正则表达式:str_extract_all

在Rstudio中使用'str_extract_all'函数(stringr)后未显示Unicode字符

使用str_extract_all在花括号之间提取字符串

str_extract_all:返回在字符串中找到的所有模式连接为向量

使用R data.table计算所有变量组合和df的不同计数

将data.table apply()中的rollapply()和weighted.mean()组合用于多列

龙目岛@Data和@Builder组合

在 Spring Data JPA 中组合和喜欢

data.frame和vector的组合

重塑和聚合data.frame的组合

data.table和列名

使用正则表达式时,使用str_replace_all()在data.table列上不起作用

\ * DATA和* DATA之间的区别

成对组合以及data.table中的计数