如何 modify/remove R 行不符合列的正则表达式模式?

How to modify/remove R rows that don't fit the regex pattern of the column?

这是我当前专栏的示例,以及我想要的替换。

Times <- c("12h00","16h30","Afternoon","15h00","14h20","7h30","06h00")
           
Output: ["12","16",NA,"15","14","7","6"]

我现在正在使用一个混乱的数据集,但我只希望该列包含每次的小时数。绝大多数采用“##h##”格式 (07h30)。

我假设 str_replace_all(Time, pattern, replacement) 可以在这种情况下工作,但我有疑问。我假设这个 "^\d{2}h\d{2}$" 是合适的代码。使不符合列模式的数据无效化的最简单方法是什么?

我的最终目标是为一天中的每个小时创建一个包含 24 个 bin 的直方图,每次都是鲨鱼袭击的发生。

你怎么看?

编辑:有一些使用#h## 格式,如“7h30”,虽然我希望用普通的“7”替换它,但由于数量很少,所以不是 100% 必要。

您可以使用

library(stringr)
Times <- c("12h00","16h30","Afternoon","15h00","14h20","7h30","06h00")
str_extract(Times, '[1-9]\d*(?=h)')
## => [1] "12" "16" NA   "15" "14" "7"  "6" 

模式将提取

  • [1-9] - 非零数字
  • \d* - 零个或多个数字
  • (?=h) - 紧随其后的是 h.

参见regex demo and the R demo