R语言如何拆分字符串为DataFrame的Datetime、MacId、RSSI多列?
R语言DataFrame字符串拆分实现方案
方法1:tidyverse生态实现(推荐用于批量处理)
依赖stringr包的正则提取功能,适配整列数据批量处理,代码如下:
# 加载依赖包 library(tidyverse) # 假设原数据框名为df,待拆分的字符串列名为raw_str df <- df %>% mutate( # 提取方括号内的时间内容 Datetime = str_extract(raw_str, "(?<=\\[).*?(?=\\])"), # 提取MacId后的硬件地址内容 MacId = str_extract(raw_str, "(?<=MacId: )[A-F0-9_]+"), # 提取RSSI后的信号值,同时转为整数格式 RSSI = as.integer(str_extract(raw_str, "(?<=RSSI: )-?\\d+")) )
方法2:Base R原生实现(无需安装额外依赖)
使用base R自带的正则匹配函数实现相同效果,代码如下:
# 提取时间列 df$Datetime <- regmatches(df$raw_str, regexpr("(?<=\\[).*?(?=\\])", df$raw_str, perl = TRUE)) # 提取MacId列 df$MacId <- regmatches(df$raw_str, regexpr("(?<=MacId: )[A-F0-9_]+", df$raw_str, perl = TRUE)) # 提取RSSI列并转为整数 df$RSSI <- as.integer(regmatches(df$raw_str, regexpr("(?<=RSSI: )-?\\d+", df$raw_str, perl = TRUE)))
两种方案均基于零宽正向预查的正则规则实现,只要所有待拆分的字符串格式和示例一致,即可直接套用。
内容的提问来源于stack exchange,提问作者Glenn
相关产品推荐
相关产品推荐

