特定の基準に基づいて、文字列 (コメント) からいくつかの数値を抽出しようとしています。抽出したい数値は、24 時間形式の日付に直接続き、常に小数点以下が含まれ、20 未満です (文字列には他の数値がありますが、これらには興味がありません)。以下の R コードを使用して必要な番号を抽出することができましたが、これらを元の ID に関連付ける方法がありません。ID には複数の対象番号があるものもあれば、1 つしかないものもあります。たとえば、以下に示すダミー データの ID 番号を対象のすべての番号に関連付ける何らかの方法が必要です。ご覧のとおり、ID 1 には 3 つの関心のある結果 (4.1、6.9、および 4.3) が含まれていますが、ID 2 には関心のある結果が 1 つしかありません (6.5)。
どんな助けでも素晴らしいでしょう!
(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)