所以我有向量,里面有参考书目
bibliography <- c("1. Cohen, A. C. (1955). Restriction and selection insamples from bivariate normal distributions. Journal
of the American Statistical Association, 50, 884–893. 2.Breslow, N. E. and Cain, K. C. (1988). Logistic regression for the two-stage case-control data.
Biometrika, 75, 11–20. 3.Arismendi, J. C. (2013). Multivariate truncated moments. Journal of Multivariate Analysis, 117, 41–75")我想在表示编号的每一个数字(即1、2和3 )之前添加新的行/换行()。因此,如果我有50条书目,我想用向量自动拆分所有字符串,并在表示编号的每个数字之前添加断线。
到目前为止,我已经尝试过这样的方法(这不是最好的选择,因为第三个参考书目被忽略了):
bibliography <- unlist(strsplit(bibliography, " "))
bibliography <- bibliography[-length(bibliography)] <- paste0(bibliography[-length(bibliography)], ' \\\\ ')输出是这样的(,这是我想要的输出):
[1] "1. Cohen, A. C. (1955). Restriction and selection in samples from bivariate normal distributions. Journal\nof the American Statistical Association, 50, 884–893. \\\\ "
[2] "2.Breslow, N. E. and Cain, K. C. (1988). Logistic regression for the two-stage case-control data.\nBiometrika, 75, 11–20. \\\\ "但这很费时,因为我不得不在每个数字(即1和2)之前手动添加双空间。这段代码才能正常工作。
我也看过这里
Add new line before every number in a string
Inserting Newline character before every number occurring in a string?
发布于 2016-09-02 10:14:28
这样你就可以得到你想要的地方了:
library(stringr)
library(dplyr)
# The first line adds the "~" character at the right break point
str_split(gsub("([1-9]\\.[]*[A-Z])","~\\1",bibliography), "~") %>%
unlist() %>%
str_trim(side = c("both")) # Trimming potential spaces at the strings sides发布于 2016-09-02 10:24:51
我尝试了一种基于正则表达式的方法
bibliography <- c("1. Cohen, A. C. (1955). Restriction and selection insamples from bivariate normal distributions. Journal of the American Statistical Association, 50, 884–893. 2.Breslow, N. E. and Cain, K. C. (1988). Logistic regression for the two-stage case-control data.
Biometrika, 75, 11–20. 3.Arismendi, J. C. (2013). Multivariate truncated moments. Journal of Multivariate Analysis, 117, 41–75")
out <- gsub("([^0-9][0-9]{1}\\.|^[0-9]{1}\\.)", "\t\\1",bibliography)
out <- unlist(strsplit(out, "\t"))
out <- gsub("^\\s+|\\s+$", "", out)
out <- out[-1]你也许可以试一试。
https://stackoverflow.com/questions/39288992
复制相似问题