2015-11-13 2 views
2

У меня есть dataframe комментариев, которая выглядит так (df1)Заполнение столбца в dataframe основанный на колонке в другом dataframe в г

Comments 
Apple laptops are really good for work,we should buy them 
Apple Iphones are too costly,we can resort to some other brands 
Google search is the best search engine 
Android phones are great these days 
I lost my visa card today 

У меня есть еще один dataframe имен merchent, который выглядит следующим образом (df2):

Merchant_Name 
Google 
Android 
Geoni 
Visa 
Apple 
MC 
WallMart 

Если MERCHANT_NAME в df2 появляется в комментарий в ДФ 1, добавьте это имя торговца к второй колонке в df1 в матче R.The не должно быть точным приближением match.An является то, что required.Also, df1 содержит около 500K строк! Мой последний ooutput ДФ может выглядеть следующим образом

Comments              Merchant 
Apple laptops are really good for work,we should buy them  Apple 
Apple Iphones are too costly,we can resort to some other brands Apple 
Google search is the best search engine       Google 
Android phones are great these days        Android 
I lost my visa card today          Visa 

Как я могу сделать это и эффективно в R. ?? Thanks

+0

Хотя название другой вопрос немного вводит в заблуждение, это на самом деле отвечает на ваш вопрос: http://stackoverflow.com/questions/33672082/if-function-on -a-for-loop/33672374 То, что вы ищете, называется объединением или объединением двух наборов данных. – David

+0

@David Я не верю, что это слияние вообще. –

+0

@ Тим, я, должно быть, пропустил часть вопросов, мои извинения. – David

ответ

5

Это работа для regex. Проверьте команду grepl внутри lapply.

comments = c(
    'Apple laptops are really good for work,we should buy them', 
    'Apple Iphones are too costly,we can resort to some other brands', 
    'Google search is the best search engine ', 
    'Android phones are great these days', 
    'I lost my visa card today' 
) 

brands = c(
    'Google', 
    'Android', 
    'Geoni', 
    'Visa', 
    'Apple', 
    'MC', 
    'WallMart' 
) 

brandinpattern = lapply(
    brands, 
    function(brand) { 
     commentswithbrand = grepl(x = tolower(comments), pattern = tolower(brand)) 
     if (sum(commentswithbrand) > 0) { 
     data.frame(
      comment = comments[commentswithbrand], 
      brand = brand 
     ) 
     } else { 
     data.frame() 
     } 
    } 
) 

brandinpattern = do.call(rbind, brandinpattern) 


> do.call(rbind, brandinpattern) 
                  comment brand 
1      Google search is the best search engine Google 
2        Android phones are great these days Android 
3          I lost my visa card today Visa 
4  Apple laptops are really good for work,we should buy them Apple 
5 Apple Iphones are too costly,we can resort to some other brands Apple 
+0

Что делать, если первый комментарий: «Google ищет лучше, чем Android»? – lawyeR

+0

@lawyeR. Код прямо там. Попробуйте. – TheComeOnMan

+0

@Codoremifa Большое спасибо за помощь .. :) – function

0

Попробуйте

final_df <- data.frame(Comments = character(), Merchant_Name = character(), stringsAsFactors = F) 

for(i in df1$Comments){ 
    for(j in df2$Merchant_Name){ 
     if(grepl(tolower(j),tolower(i))){ 
      final_df[nrow(final_df) + 1,] <- c(i, j) 
      break 
     } 
    } 
} 


final_df 

##              comments brands 
##1  Apple laptops are really good for work,we should buy them Apple 
##2 Apple Iphones are too costly,we can resort to some other brands Apple 
##3      Google search is the best search engine Google 
##4        Android phones are great these days Android 
##5          I lost my visa card today Visa 

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

  • Нет связанных вопросов^_^