2016-09-02 2 views
2

前に休憩を追加だから私は、私が分割文字列を好きで、新しい行/改行の番号を表し、すべての番号の前にを追加することになり、書誌分割文字列とすべての番号

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の参考文献を言うならば、私は自動的にベクトル内のすべての文字列を分割し、番号付けを表すすべての数字の前に改行を追加したいと思います。

これまでのところ、私は(第3 bibliograhpyが取り残されるよう最善の選択肢ではありません)、これを試してみた:

bibliography <- unlist(strsplit(bibliography, " ")) 
    bibliography <- bibliography[-length(bibliography)] <- paste0(bibliography[-length(bibliography)], ' \\\\ ') 

、出力はこの(MY所望の出力 IS )であった。

しかし、このコードが機能するためには、すべての数値(つまり、1.と2.)の前に手動で二重のスペースを追加する必要があったため、時間がかかります。

は、私はまた、これはあなたがしたい場所はかなりあなたを取得ここ

Add new line before every number in a string

Inserting Newline character before every number occurring in a string?

答えて

2

見てきました:

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 
1

が、私は正規表現ベースのアプローチを試してみました

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] 

あなたはおそらくそれを打つことができます。