1
아래와 같은 attributes.txt 파일 (Sawtooth 조사 연구 결과)을 파싱하여 출력 결과가 아래와 같이 표시되도록하고 싶습니다. 아래에서 내 시도를 볼 수 있습니다. 그것은 작동합니다. 그러나 그것은 매우 추합니다. 더 좋은 방법이있을거야, 맞지? (그들이 사용할 수 있다면 나는 tidyverse 솔루션을 선호)R 구조의이 구조화 된 텍스트 파일 구문 분석
attributes.txt :
attribute,level,label
1,1,brand01
1,2,brand02
1,3,brand03
1,4,otherbrand
2,1,1
2,2,2
2,3,3
2,4,4
2,5,5
3,1,99
3,2,199
3,3,299
내 시도 :
분석에서================================================================================
ATTRIBUTES AND LEVELS
================================================================================
========================================
Display Text
========================================
<Same structure as shown below. But I do not want to extract any of this text>
========================================
Internal Labels
========================================
[Attribute List]:
1 brand
2 rating
3 price
---------------------------
Attribute 1:
brand
Levels:
1 brand01
2 brand02
3 brand03
4 otherbrand
---------------------------
Attribute 2:
rating
Levels:
1 1
2 2
3 3
4 4
5 5
---------------------------
Attribute 3:
price
Levels:
1 99
2 199
3 299
원하는 출력
library(stringr) parse_attributes_file <- function(ATTRIBUTES_FILE_PATH) { con = file(ATTRIBUTES_FILE_PATH, "r") reached_internal_labels <- FALSE attribute_num <- NA datalist <- list() idx <- 0 while (TRUE) { line = readLines(con, n = 1) if (length(line) == 0) { break } if (!reached_internal_labels) { reached_internal_labels <- str_detect(line, "Internal Labels") } else { attribute_num_extract <- str_match(line, "Attribute ([[:digit:]]+): ")[,2] if(!is.na(attribute_num_extract)) { attribute_num <- attribute_num_extract } else { if (!is.na(attribute_num)) { my_match <- str_match(line, "([[:digit:]]+)\t(.*)") if(!is.na(my_match[,1])) { idx <- idx + 1 datalist[[idx]] <- c(attribute_num, my_match[,2], my_match[,3]) } } } } } close(con) attributes = do.call(rbind, datalist) colnames(attributes) <- c("attribute", "level", "label") return(attributes) }
조금 펑키. 나 한테 줄곧 몰랐어. 그러나 이것이 내가 본 최고의 것입니다. 그래서 답으로 표시하십시오. – lowndrul