2016-08-13 9 views
1

특정 조건에 따라 문자열에서 일부 숫자를 추출하려고합니다 (주석). 내가 직접 추출하고자하는 숫자는 24 시간 형식의 날짜를 따르고 항상 소수 자리를 포함하며 20 미만입니다 (문자열에 다른 숫자가 있지만 이것들에는 관심이 없습니다). 나는 아래의 R 코드를 사용하여 원하는 숫자를 추출 할 수 있었지만이 코드를 원래 ID와 연관시키는 방법이 없습니다. 일부 ID는 여러 개의 관심 분야가 있지만 일부는 유일한 관심 분야입니다. 예를 들어, 아래에 제공된 더미 데이터의 ID 번호를 관심있는 모든 번호와 연관시키는 방법이 필요합니다. ID 1에는 3 개의 관심 결과 (4.1, 6.9 및 4.3)가 포함되어있는 반면, ID 2에는 관심있는 결과 (6.5)는 1 개뿐입니다.특정 조건을 기반으로 R의 문자열에서 숫자 추출

도움이 될 것입니다. 이 같은

(An example of the format of comment.txt) 

    ID comments 
    1 abc1200 4.1 abc1100 6.9 etd1130 4.3 69.0 
    2 abc0900 6.5 abcde 15 
    3 3.2 0850 9.5 abc 8.2 0930 12.2 agft 75.0 
    4 ashdfalsk 0950 10.5 dvvxcvszv asdasd assdas d 75.0 


#rm(list=ls(all=TRUE)) 

#import text and pull out a list of all numbers contained withtin the free text 
raw_text <- read.delim("comment.txt") 
numbers_from_text <- gregexpr("[0-9]+.[0-9]", raw_text$comments) 

numbers_list <- unlist(regmatches(raw_text$comments, numbers_from_text)) 
numbers_list <- as.data.frame(numbers_list) 

#pull out those numbers that contain an decimal place and create a running count 
format<-cbind(numbers_list,dem=(grepl("\\.",as.character(numbers_list$numbers_list)))*1,row.number=1:nrow(numbers_list)) 

#if the number does not contain a decimal (a date) then create a new row number which is the addition of the first row 
#else return NA 
test <- cbind(format,new_row = ifelse(format$dem==0, format$row.number+1, "NA")) 

#match the cases where the new_row is equal to the row.number and then output the corresponding numbers_list 
match <-test$numbers_list[match(test$new_row,test$row.number)] 

#get rid of the NA's for where there wasnt a match and values less than 20 to ensure results are correct 
match_NA <- subset(match, match!= "<NA>" & as.numeric(as.character(match))<20) 

match_NA <- as.data.frame(match_NA) 

답변

0

뭔가는 숫자과 1 미만 (20)

library(stringr) 
temp <- apply(comments, 1, function(x) { 
    str_extract_all(x,"[[:blank:]][0-9]+[.][0-9]") 
}) 

library(purrr) 
temp <- lapply(flatten(temp), function(x) as.numeric(str_trim(x))) 
lapply(temp, function(x) x[x <20]) 

[[1]] 
[1] 4.1 6.9 4.3 

[[2]] 
[1] 6.5 

[[3]] 
[1] 3.2 9.5 8.2 12.2 

[[4]] 
[1] 10.5 
이다 추출로 전환하는 기간을 포함하는 빈으로 시작 수치를 일치 작동하는 것 같다