我得到了一个向量字符串,如下所示:
t1 <- " Total"
t2 <- " Total Stock Price"
t3 <- " Dividend Misc Gain MTCC Gain Gain"
t4 <- " Proportion Gain Position Position Position"
t5 <- " Year Dividend Gain Earned (1) x (2) Dividend Gain Misc Gain (4) - (5) (3) - (4) (6) + (7)"
t6 <- " ––––– ––––– ––––– ––––– ––––– ––––– ––––– ––––– –––––"
t <- c(t1, t2, t3, t4, t5, t6)
从上面可以看到,它是表格的标题,该表格的标题与最后一个元素 t6 对齐。
现在,我正在尝试获取上述每列中最长单词的开始和结束索引。
例如,第3列是
Proportion
Earned
–––––
最长的单词是Proportion
,然后我将尝试在 t4 中找到Proportion
的开始和结束索引。
另一个例子是第2列
Dividend Gain
–––––
最长的单词是Dividend Gain
,我将尝试在 t5 中找到Dividend Gain
的开始和结束索引。
如何从 t 中找到所需的索引?
答案 0 :(得分:2)
一种解决方案是匹配所有矢量的字符位置。
首先,如果所有字符串都具有相同数量的字符,可能会有所帮助。我们可以通过在末尾添加一些空格来实现此目的。
# list string vector --
tl <- as.list(tx)
# make equal length --
tl <- lapply(tl, function(x) {
d <- max(sapply(tl, nchar)) - nchar(x)
if (d > 0) paste(x, Reduce(paste0, rep(" ", d - 1)))
else x
})
# check equal num. of chars.
sd(sapply(tl, nchar))
# [1] 0 # ok
然后,我们编写一个split函数,该函数在序列跳转时剪切一个向量。
splitAtCuts <- function(x)
split(x, cut(x, x[which(c(2, diff(x[- length(x)]), length(x)) > 1)],
include.lowest=TRUE, right=FALSE))
现在我们可以分两个步骤匹配字符位置。
# get character position matches --
# step 1
sl <- lapply(tl, function(x) {
w <- which(strsplit(x, "")[[1]] != " ")
return(splitAtCuts(w))
})
# step 2
pos <- sort(Reduce(union, unlist(sl)))
现在我们知道了字符在哪里,我们可以得出列的位置,
# extract column positions --
cols <- splitAtCuts(pos)
这有助于我们将字符串列表切成所需的矩阵。
# cut into a matrix --
FUN <- Vectorize(function(x, y)
substring(tl[[x]], min(cols[[y]]), max(cols[[y]])))
M <- outer(seq(length(tl)), seq(length(cols)), FUN)
最后我们进行一些清洁。
M <- apply(M, 2, function(x) gsub("^\\s|\\s{2,}|\\s$", "", x))
M
屈服
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "" "" "" "" "" ""
[2,] "" "" "" "Total" "" ""
[3,] "" "" "" "Dividend" "" ""
[4,] "" "" "Proportion" "Gain" "" ""
[5,] "Year" "Dividend Gain" "Earned" "(1) x (2)" "Dividend Gain" "Misc Gain"
[6,] "–––––" "–––––" "–––––" "–––––" "–––––" "–––––"
[,7] [,8] [,9]
[1,] "" "" "Total"
[2,] "" "" "Stock Price"
[3,] "Misc Gain" "MTCC Gain" "Gain"
[4,] "Position" "Position" "Position"
[5,] "(4) - (5)" "(3) - (4)" "(6) + (7)"
[6,] "–––––" "–––––" "–––––"
数据
tx <- c(" Total",
" Total Stock Price",
" Dividend Misc Gain MTCC Gain Gain",
" Proportion Gain Position Position Position",
" Year Dividend Gain Earned (1) x (2) Dividend Gain Misc Gain (4) - (5) (3) - (4) (6) + (7)",
" ––––– ––––– ––––– ––––– ––––– ––––– ––––– ––––– –––––"
)