Объединить вектор в информационный кадр - PullRequest
0 голосов
/ 05 июня 2019

Я хочу преобразовать вектор в кадр данных.Вектор состоит из уникального идентификатора, за которым следуют другие поля.Поля являются исчерпывающими, около 30 различных полей, все отмечены обратной косой чертой.

\ID a 
\description text yes 
\definition text yes 
\other.info text yes 
\ID b 
\definition text yes 
\other.info text yes 
\ID d 
\description text yes 
\other.info text yes 
\translation text yes

Мне нужно преобразовать это в:

ID  description  definition  other.info  translation
 a   text yes     text yes    text yes
 b                text yes    text yes
 d   text yes                 text yes    text yes

Спасибо за вашу помощь

1 Ответ

0 голосов
/ 06 июня 2019

Вот что-то быстрое и грязное, но выполняет свою работу:

library(stringr) # Will use str_extract() with some regex
library(magrittr) # pipes: %>%
library(data.table) # rbindlist (I think dplyr has bind_rows() which is similar)

split(vect, cumsum(grepl("ID", vect))) %>% 
  lapply(function(x) setNames(data.frame(t(str_extract(x, "\\w+$"))), str_extract(x, "^.+\\s")) ) %>% 
  rbindlist(fill = TRUE) %>% 
  setNames(gsub("text|\\\\", "", names(.)))


   ID  description   definition   other.info   translation  
1:   a           yes          yes          yes          <NA>
2:   b          <NA>          yes          yes          <NA>
3:   d           yes         <NA>          yes           yes

Данные :

vect <- c("\\ID a", "\\description text yes", "\\definition text yes", "\\other.info text yes", 
"\\ID b", "\\definition text yes", "\\other.info text yes", "\\ID d", 
"\\description text yes", "\\other.info text yes", "\\translation text yes"
)
...