2017-12-13 29 views
1

필자는 함수를 작성하거나 적용 패밀리를 사용하여 찾고있는 단어가 들어있는 데이터 프레임의 행을 선택하고 태그처럼 표시하려고 시도했습니다. 행은 여러 개의 태그를 가질 수 있습니다. 누군가 나를 도와주세요, 나는 잠시 붙어 있습니다.데이터 프레임의 행을 반복 처리하여 다른 단어를 찾아 새 열에 저장하려면 어떻게합니까?

제 질문이 명확하지 않거나 다른 곳에서 답변이 있으면 저를 올바른 방향으로 인도하십시오. 매우 감사!

require(stringr) 
require(dplyr) 
df <- data.frame(sentences, rnorm(length(sentences))) 

old = df %>% filter(str_detect(sentences, 'old')) %>% mutate(w = factor("old")) 
new = df %>% filter(str_detect(sentences, 'new')) %>% mutate(w = factor("new")) 
boy = df %>% filter(str_detect(sentences, 'boy')) %>% mutate(w = factor("boy")) 
girl = df %>% filter(str_detect(sentences, 'girl')) %>% mutate(w = factor("girl")) 
tags <- bind_rows(old, new, boy, girl) 

그래서 예를 들어 단어의 유한 수를 선택합니다 :

tags <- c('bananas', 'apples', oranges) 

그리고 결과는 내가 선택한 모든 단어에 대한 새로운 열이있는 data.frame되고 싶어요. 행에 내가 선택한 단어 중 하나가 포함되어 있으면 해당 단어의 열이 어떻게 든 표시되어야합니다. 그런

Sentences  bananas  apples  oranges 
sentence1  TRUE   
sentence2     TRUE 
sentence3  TRUE 
sentence4       TRUE 
sentence5     TRUE  TRUE 

또는

Sentences  tag1  tag2 
sentence1  bananas   
sentence2  apples 
sentence3  bananas 
sentence4  oranges 
entences5  apples  oranges 

또는 뭔가 비슷 해요. 더 명확하게 설명 할 수 있으면 알려주십시오.

+1

찾고있는 최종 해결책은 무엇입니까? 개념적으로, 그것은 무엇을 할 수 있습니까? –

+0

태그하려는 단어의 한정된 알려진 양이 있습니까? – LAP

+0

나는 조금 더 설명하려고 노력했다. 단어의 수는 유한 한 예이며 모든 단어가 포함되어 있으면 모든 행에 태그를 추가하려고한다. 나는 모든 단어 나 태그 # 1 # 2 # 3의 최대 열 (태그의 nr)에 이르기까지 무엇이 좋을지 모릅니다. – CluelessCoder

답변

0

실제로 적용 기능을 사용 하시겠습니까? 나는 tm 패키지를 찾고 있습니다. 이것은 가장 쉽고 강력한 방법 인 입니다.. DocumentTermMatrix 기능을 사용하면 원하는 것을 얻을 수 있습니다. 필자는 (구문 수준이 높은) 내 문장을 정교하게 작성했다. 가장 쉬운 방법은 모든 단어와 을 진행하고을 찾으려는 단어 열을 선택하면됩니다.

sentence1 <- "This is a bananana" 
sentence2 <- "This is an apple" 
sentence3 <- "This is a watermelon and a banana" 
sentence4 <- "This is a watermelon a banana an apple" 

df_sentence <- rbind(sentence1, sentence2, sentence3, sentence4) 

library(tm) 
vs_sentence <- VectorSource(df_sentence) 
vc_sentence <- VCorpus(vs_sentence) 

clean_sentence <- tm_map(vc_sentence, removePunctuation) 
dtm_sentence <- DocumentTermMatrix(clean_sentence) 
as.matrix(dtm_sentence) 

결과 : 당신이 을 제공 할 수있는 경우

as.matrix(TermDocumentMatrix(clean_sentence)) 
      Docs 
Terms  1 2 3 4 
    and  0 0 1 0 
    apple  0 1 0 1 
    banana  1 0 1 1 
    this  1 1 1 1 
    watermelon 0 0 1 1 

:

 Terms 
Docs and apple banana this watermelon 
    1 0  0  1 1   0 
    2 0  1  0 1   0 
    3 1  0  1 1   1 
    4 0  1  1 1   1 
또한

는 행에 의해 열과 용어로 문서를 얻을 수 있습니다 또 다른 기능있다 문장의 일부로 더 나은 해결책을 제공하기가 더 쉬울 수도 있습니다. HTH!