【发布时间】:2018-01-17 21:52:11
【问题描述】:
我需要按字数将字符串分成两半(当单词数为奇数时,中间的单词应该出现在左侧和右侧)。我还需要知道每个字符串来自哪一侧。
my_question <- data.frame(string_id = c(001, 002, 003),
string = (c("how do I split", "how do I split this", "how do I split this string")))
my_answer <- data.frame(string_id = c(001, 002, 003, 001, 002, 003),
string = (c("how do", "how do I", "how do I", "I split", "I split this", "split this string")),
side = c("R", "R", "R", "L", "L", "L"))
我更喜欢使用 stringr/tidyverse/hadleyverse。
【问题讨论】:
-
你已经尝试过了......
-
第 1 步使用
strsplit拆分。第 2 步创建索引 1:n/2 和 n/2:n 的向量,其中 n 是第 1 步结果的长度。第一个索引位于左侧,第二个位于右侧。使用paste和collapse=' '将两侧重新组合在一起。尝试一下,如果遇到问题,请提出更具体的问题。 -
另外,请查看
?strwrap和library(stringr); ?str_wrap了解文本换行是如何实现的
标签: r string split tidyverse stringr