2015-07-25 3 views
0

У меня есть следующие данные в кадре данных:согласования текста между двумя различными кадрами данных в R

structure(list(`head(ker$text)` = structure(1:6, .Label = c("@_rpg_17 little league travel tourney. These parents about to be wild.", 
"@auscricketfan @davidwarner31 yes WI tour is coming soon", "@keralatourism #favourite #destination #munnar #topstation https://t.co/sm9qz7Z9aR", 
"@NWAWhatsup tour of duty in NWA considered a dismal assignment? Companies send in their best ppl and then those ppl don't want to leave", 
"Are you Looking for a trip to Kerala? #Kerala-prime tourist attractions of India.Visit:http://t.co/zFCoaoqCMP http://t.co/zaGNd0aOBy", 
"Are you Looking for a trip to Kerala? #Kerala, God's own country, is one of the prime tourist attractions of... http://t.co/FLZrEo7NpO" 
), class = "factor")), .Names = "head(ker$text)", row.names = c(NA, 
-6L), class = "data.frame") 

У меня есть другой кадр данных, который содержит хештег извлеченных из приведенных выше кадра данных. Она заключается в следующем:

structure(list(destination = c("#topstation", "#destination", "#munnar", 
"#Kerala", "#Delhi", "#beach")), .Names = "destination", row.names = c(NA, 
6L), class = "data.frame") 

Я хочу, чтобы создать новый столбец в моем первом кадре данных, которые будут иметь содержать только теги совпавшие со второго кадра данных. Например, в первой строке df1 нет хэштегов, поэтому эта ячейка в новом столбце будет пустым. Однако вторая строка содержит 4 хэштага, из которых три из них соответствуют второму кадру данных. Я попытался использовать:

str_match 
str_extract 

функции. Я пришел очень близко к этому, используя код, приведенный в одном из сообщений здесь.

new_col <- ker[unlist(lapply(destn$destination, agrep, ker$text)), ] 

В то время как я понимаю, я получаю список как выход я получаю сообщение об ошибке, указывающее

replacement has 1472 rows, data has 644 

Я попытался установить max.distance различным параметрам, каждый дал мне дифференциальные ошибки. Может ли кто-нибудь помочь мне с решением? Одна из альтернатив, о которой я думаю, состоит в том, чтобы иметь каждый хэштег в отдельном столбце, но не уверен, поможет ли он мне в дальнейшем анализировать данные с другими переменными, которые у меня есть. Выход Ищу выглядит следующим образом:

text   new_col   new_col2 new_col3 
statement1  
statement2 
statement3 #destination  #munnar  #topstation 
statement4 
statement5 #Kerala 
statement6 #Kerala 

ответ

0
library(stringi); 
df1$tags <- sapply(stri_extract_all(df1[[1]],regex='#\\w+'),function(x) paste(x[x%in%df2[[1]]],collapse=',')); 
df1; 
##                                head(ker$text)        tags 
## 1                 @_rpg_17 little league travel tourney. These parents about to be wild. 
## 2                     @auscricketfan @davidwarner31 yes WI tour is coming soon 
## 3              @keralatourism #favourite #destination #munnar #topstation https://t.co/sm9qz7Z9aR #destination,#munnar,#topstation 
## 4 @NWAWhatsup tour of duty in NWA considered a dismal assignment? Companies send in their best ppl and then those ppl don't want to leave 
## 5  Are you Looking for a trip to Kerala? #Kerala-prime tourist attractions of India.Visit:http://t.co/zFCoaoqCMP http://t.co/zaGNd0aOBy       #Kerala 
## 6 Are you Looking for a trip to Kerala? #Kerala, God's own country, is one of the prime tourist attractions of... http://t.co/FLZrEo7NpO       #Kerala 

Edit: Если вы хотите отдельный столбец для каждого тега:

library(stringi); 
m <- sapply(stri_extract_all(df1[[1]],regex='#\\w+'),function(x) x[x%in%df2[[1]]]); 
df1 <- cbind(df1,do.call(rbind,lapply(m,`[`,1:max(sapply(m,length))))); 
df1; 
##                                head(ker$text)   1  2   3 
## 1                 @_rpg_17 little league travel tourney. These parents about to be wild.   <NA> <NA>  <NA> 
## 2                     @auscricketfan @davidwarner31 yes WI tour is coming soon   <NA> <NA>  <NA> 
## 3              @keralatourism #favourite #destination #munnar #topstation https://t.co/sm9qz7Z9aR #destination #munnar #topstation 
## 4 @NWAWhatsup tour of duty in NWA considered a dismal assignment? Companies send in their best ppl and then those ppl don't want to leave   <NA> <NA>  <NA> 
## 5  Are you Looking for a trip to Kerala? #Kerala-prime tourist attractions of India.Visit:http://t.co/zFCoaoqCMP http://t.co/zaGNd0aOBy  #Kerala <NA>  <NA> 
## 6 Are you Looking for a trip to Kerala? #Kerala, God's own country, is one of the prime tourist attractions of... http://t.co/FLZrEo7NpO  #Kerala <NA>  <NA> 
+1

Большое спасибо, bgoldst, это сработало! ... вот ... это было сложно для меня ... еще раз спасибо. – Apricot

0

Вы могли бы сделать что-то вроде этого:

library(stringr) 
results <- sapply(df$`head(ker$text)`, 
        function(x) { str_match_all(x, paste(df2$destination, collapse = "|")) }) 

df$matches <- results 

Если вы хотите, чтобы отделить результаты, вы можете использовать:

df <- cbind(df, do.call(rbind, lapply(results, [ , 1:max(sapply(results, length)))))

+0

Большое спасибо JasonAiskalns .... Я работал частично, снабдив меня как в заявлении, а также хэштегом .... Я бы требовать только хештегов .. . Я обновил запрос снова, указав вывод – Apricot

+0

. Я попытался использовать ваш код, изменив str_match_all на str_match ... получил результат ... но предоставил только один из хэштегов для оператора 3 вместо 3 хэштегов .... – Apricot

+0

@ MageshGovindan. Вы уверены, что когда я смотрю на 'df' и смотрю на столбец' match' для оператора 3, я вижу все три хэштега, разделенные запятой. – JasonAizkalns

Смежные вопросы