我遇到了找到正确的正则表达式以将单个列分成两个的麻烦。
这是我的榜样。
Col 1
8.3 algo y algo mas
我想要这个
Col 1 Col 2
8.3 algo y algo mas
我一直在尝试这段代码。
library(tidyverse)
base <- base %>%
separate(col 1, into c("col 2", "col 3"), sep = "\\s")
答案 0 :(得分:0)
为了安全起见,我认为最好用一个容易识别字符的数字替换每个空格......
df[, 'Col 1'] <- gsub(pattern = '^([0-9\\.]+) ', replacement = '\\1_', x = df[, 'Col 1'])
然后我会使用separate
:
df <- separate(data = df, col = 'Col 1', into = c('Col 1', 'Col 2'), sep = '_')
我还会更改列名称,因为在列名称中空格通常是个问题...尝试更改为col_1
之类的内容。
答案 1 :(得分:0)
您可以尝试stringr
和rebus
:
df <- data.frame(Col_1 = "8.3 algo y algo mas")
library(stringr)
library(rebus)
str_match(df$Col_1, pattern = capture(DGT %R% DOT %R% DGT) %R%
SPC %R%
capture(one_or_more(or(SPC, LOWER))))
rebus
包允许您使用人类可读代码逐个构建正则表达式。输出如下:
# [,1] [,2] [,3]
# [1,] "8.3 algo y algo mas" "8.3" "algo y algo mas"