R:从字符串中删除最后三个点

Mar*_*ler 5 regex r

我有一个我可能会阅读的文本数据文件readLines.每个字符串的初始部分包含大量的乱码,然后是我需要的数据.乱码和数据通常由三个点分隔.我想在最后三个点之后拆分字符串,或者用某种标记替换最后三个点,告诉R将这三个点左边的所有内容都当作一列.

这是Stackoverflow上的一个类似帖子,它将找到最后一个点:

R:找到字符串中的最后一个点

但是,在我的情况下,一些数据有小数,所以找到最后一个点是不够的.另外,我认为...R中有一个特殊的含义,这可能会使问题复杂化.另一个潜在的复杂因素是一些点比其他点大.此外,在某些行中,三个点中的一个用逗号替换.

除了gregexpr在上面的帖子我尝试过使用gsub,但无法弄清楚解决方案.

这是一个示例数据集和我希望实现的结果:

aa = matrix(c(
'first string of junk... 0.2 0 1', 
'next string ........2 0 2', 
'%%%... ! 1959 ...  0 3 3',
'year .. 2 .,.  7 6 5',
'this_string   is . not fine .•. 4 2 3'), 
nrow=5, byrow=TRUE,
dimnames = list(NULL, c("C1")))

aa <- as.data.frame(aa, stringsAsFactors=F)
aa

# desired result
#                             C1  C2 C3 C4
# 1        first string of junk  0.2  0  1
# 2            next string .....   2  0  2
# 3             %%%... ! 1959      0  3  3
# 4                 year .. 2      7  6  5
# 5 this_string   is . not fine    4  2  3
Run Code Online (Sandbox Code Playgroud)

我希望这个问题不要太具体.文本数据文件是使用我昨天发布的关于在R中读取MSWord文件的帖子中概述的步骤创建的.

有些线条不包含乱码或三个点,但只包含数据.然而,这可能是后续帖子的复杂因素.

谢谢你的任何建议.

Mat*_*ker 5

这样做虽然不是特别优雅......

options(stringsAsFactors = FALSE)


# Search for three consecutive characters of your delimiters, then pull out
# all of the characters after that
# (in parentheses, represented in replace by \\1)
nums <- as.vector(gsub(aa$C1, pattern = "^.*[.,•]{3}\\s*(.*)", replace = "\\1"))

# Use strsplit to break the results apart at spaces and just get the numbers
# Use unlist to conver that into a bare vector of numbers
# Use matrix(, nrow = length(x)) to convert it back into a
# matrix of appropriate length
num.mat <- do.call(rbind, strsplit(nums, split = " "))


# Mash it back together with your original strings
result <- as.data.frame(cbind(aa, num.mat))

# Give it informative names
names(result) <- c("original.string", "num1", "num2", "num3")
Run Code Online (Sandbox Code Playgroud)