这里是我写的,打破了长串入行不大于给定长度长串插入换行符 - 自动换行
strBreakInLines <- function(s, breakAt=90, prepend="") {
words <- unlist(strsplit(s, " "))
if (length(words)<2) return(s)
wordLen <- unlist(Map(nchar, words))
lineLen <- wordLen[1]
res <- words[1]
lineBreak <- paste("\n", prepend, sep="")
for (i in 2:length(words)) {
lineLen <- lineLen+wordLen[i]
if (lineLen < breakAt)
res <- paste(res, words[i], sep=" ")
else {
res <- paste(res, words[i], sep=lineBreak)
lineLen <- 0
}
}
return(res)
}
它适用于我的问题不再是一个功能;但我想知道我能否在这里学到一些东西。是否有更短或更有效的解决方案,特别是我可以摆脱for循环?
伟大的解决方案!我觉得我需要了解正则表达式,谢谢你指出我的函数中的错误。 – 2010-02-28 18:53:48
你能否添加一个注释来解释每个部件具体做什么? – theforestecologist 2017-01-21 23:59:44