Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中寻找模式_R_For Loop_If Statement_Pattern Matching - Fatal编程技术网

在R中寻找模式

在R中寻找模式,r,for-loop,if-statement,pattern-matching,R,For Loop,If Statement,Pattern Matching,我正试图清理一些数据。下面是我的数据示例 test1 test2 test3 jsb cjn kd N069W j N9DSW 我想指出哪个列中有模式N0{num}{num}W。{num}部分可以是0-9之间的任何数字。此模式也可以出现在字符串中的任何位置。因此,在这种情况下,我的结果如下 test1 test2 test3 col jsb cjn kd

我正试图清理一些数据。下面是我的数据示例

   test1          test2         test3    
 jsb cjn       kd N069W j        N9DSW 
我想指出哪个列中有模式N0{num}{num}W。{num}部分可以是0-9之间的任何数字。此模式也可以出现在字符串中的任何位置。因此,在这种情况下,我的结果如下

   test1          test2         test3     col
 jsb cjn       kd N069W j        N9DSW      2

提前感谢您的帮助。

我们循环浏览列,使用
grepl
获取逻辑索引,然后使用
max.col
获取每行的列索引

max.col(data.frame(lapply(df1, grepl, pattern = "N0\\d{2}W")))
#[1] 2
数据
df1您还可以使用库stringr中的函数
stru detect()

library(stringr)
str_detect('kd NO69W j', pattern = "NO\\d+W")
# [1] TRUE

使用
应用

df$col <- apply(df, 1, function(x) grep("N0\\d{2}W", x))

df$col如果模式似乎有两个数字,正则表达式不应该是
“NO\\d\\dW”
?我假设d+w查找数字,出于好奇,您如何搜索a-z之间的字母@Demarsylvai您可以查找“正则表达式”。参数
pattern=
将接受其中大部分()。例如,
str\u detect(character\u value,pattern=“[a-zA-Z]”
df$col <- apply(df, 1, function(x) grep("N0\\d{2}W", x))
df <- structure(list(test1 = structure(1L, .Label = "jsb cjn", class = "factor"), 
    test2 = structure(1L, .Label = "kd N069W j", class = "factor"), 
    test3 = structure(1L, .Label = "N9DSW ", class = "factor")), class = "data.frame", row.names = c(NA, 
-1L))