【问题标题】:R: Splitting a string into multiple columnsR:将字符串拆分为多列
【发布时间】:2021-10-29 21:03:57
【问题描述】:
我正在使用数据框中的以下列字符串
s <- "[08/26/2021 06:58:12 260] - MacId: 40_E3_D6_CA_56_5C RSSI: -92"
我想以某种方式将其拆分为以下列
- df$Datetime = 08/26/2021 06:58:12 260
- df$MacId = 40_E3_D6_CA_56_5C
- df$RSSI = -92
有没有这样的功能?
【问题讨论】:
标签:
r
dataframe
split
strsplit
【解决方案1】:
您可以使用strcapture 并传递模式以提取所需的数据。
s <- "[08/26/2021 06:58:12 260] - MacId: 40_E3_D6_CA_56_5C RSSI: -92"
result <- strcapture('\\[(.*)\\] - MacId: (.*) RSSI: (.*)', s,
proto = list(Datetime = character(), MacId = character(),
RSSI = numeric()))
result
# Datetime MacId RSSI
#1 08/26/2021 06:58:12 260 40_E3_D6_CA_56_5C -92
如果字符串存在于数据框中,则可以在 tidyr::extract 中使用相同的正则表达式模式 -
tidyr::extract(data.frame(s), s, c('Datetime', 'MacId', 'RSSI'),
"\\[(.*)\\] - MacId: (.*) RSSI: (.*)")