2016-01-27 34 views
-1

在R,尋找一個功能中另一行的值計算一行值(完全串)的發生 例如:數據表DFř計數行字符串值的出現在另一行字符串

df$SerachingFor df$Target        df$SearchTermOccurrencesInTarget (required field) 
Machine rowing machine rowing has two values   1 
handy tools  handy tools, we have many handy tools 2 
plans   home plans, garden plans, DIY plans  3 
hospital   home ideas        0 

感謝您的時間

+0

喔,好像有人不喜歡我的問題,但在stri_count_regex下面的答案試圖爲錯誤(字符串,圖案,opts_regex =屬性(模式得到一個錯誤,:在正規表達式模式 語法錯誤( U_REGEX_RULE_SYNTAX) – prav

回答

2

以下是一個使用stringr函數庫的方法。請注意,我將這兩列轉換爲全部小寫字母,因爲您的示例意味着不區分大小寫的匹配。

library(stringr) 
df$SerachingFor <- tolower(df$SerachingFor) 
df$Target <- tolower(df$Target) 
df$SearchTermOccurrencesInTarget <- str_count(df$Target, df$SerachingFor) 
df 
    SerachingFor        Target SearchTermOccurrencesInTarget 
1 machine rowing   machine rowing has two values        1 
2 handy tools handy tools we have many handy tools        2 
3   plans  home plans garden plans DIY plans        3 
4  hospital       home ideas        0 
+0

謝謝你的回答,但是在stri_count_regex(string,pattern,opts_regex = attr(pattern,: )語法錯誤中得到錯誤(U_REGEX_RULE_SYNTAX) - 這裏有任何幫助 – prav

+0

你可以不改變(df,str_count(tolower(Target),tolower(SerachingFor)))'。 –

+0

Richard,謝謝你的回答,但是出現錯誤U_REGEX_RULE_SYNTAX錯誤我的原始數據,並保存了幾行代碼, n stri_count_regex(string,pattern,opts_regex = attr(pattern,: 正則表達式模式中的語法錯誤。 (U_REGEX_RULE_SYNTAX)。請幫助任何幫助 – prav

相關問題