2016-09-02 3 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 권의 서지를 말한다면, 자동으로 모든 문자열을 벡터로 분리하고 번호 매기기를 나타내는 모든 숫자 앞에 나누기를 추가하고 싶습니다.

지금까지 내가 (교체 아웃 남아있는 세 번째 bibliograhpy으로 최선의 선택하지 않은)이 시도했습니다

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

가 출력이 (MY 원하는 출력입니다 )이었다

[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?

답변

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] 

당신은 아마 그것을 쏠 수 있습니다.

관련 문제