从一列中返回任意 n 个连续数字的字符串

Return any string of n contiguous numbers from a column

提问人:Mark 提问时间:10/29/2022 更新时间:10/29/2022 访问量:38

问:

假设我有一个数据集:

有:

example1 example2
11-2001-6 st3829s
11-2001-6 s8290s
11-201-6 sts39

要:

example1 example2
2001 3829
2001 8290
NA NA

我想输出 4 个连续数字或 n 个数字(指定长度)。 如果没有一组 4 个数字一起出现,则返回 NA。

R 数据库 数据操作

评论


答:

-1赞 abdul rahman souda 10/29/2022 #1

首先,我们谈论的是正则表达式。 其次,我将使用PHP语言解决这个问题,您应该找到适合您的程序语言的解决方案

preg_match_all('/[0-9][0-9][0-9][0-9]/', '11-2001-6 st3829s', $output_array);

这将输出

array(1
0   =>  array(2
0   =>  2001
1   =>  3829
)
)

但是如果你路径

preg_match_all('/[0-9][0-9][0-9][0-9]/', '11-201-6 sts39', $output_array);

这将输出

array(1
0   =>  array()
)

所以你检查了输出,如果它是空的数组,你就返回 NA

评论

2赞 Jilber Urbina 10/29/2022
嗨@abdul rahman souda,这是一个特定于 R 的问题,即使您回答了您的问题,您也使用了另一种语言
0赞 Jilber Urbina 10/29/2022 #2

我们可能使用str_extractmutate_all

library(stringr)
library(dplyr)
mutate_all(df,  ~str_extract(., pattern= "\\d{4}"))
 example1 example2
1     2001     3829
2     2001     8290
3     <NA>     <NA>

评论

0赞 Mark 10/29/2022
是否可以仅将此模式查找应用于一个变量?
0赞 Jilber Urbina 10/29/2022
是的,它是!try this 仅适用于mutate(df, example1 = str_extract(example1, pattern= "\\d{4}"))example1