2017-02-02 23 views
1

我試着按這個數據使得函數依賴於兩個變量匹配合適的人選 - R的

girlfriend = c('Sue','Julie','Lora','Lora','Julie') 
boyfriend = c('Sam','John','Peter','Chris','Sam') 
goodfeeling = c(88, 78, 63,  51, 40) 
couple = data.frame(girlfriend,boyfriend,goodfeeling) 

通過上面的數據做出couplemaker功能,我想最好的男孩匹配的女孩。

A = 'Julie (Sam|John|Peter)' 

A 
[1] 'Julie (John)' 

爲了對付這個字符串,下面的代碼是如此usful。

gsubfn("\\(([^)]+)", ~paste0("(", paste(couplemaker(unlist(x)), collapse="|")), A) 

但是,重要的功能是couplemaker()我應該做的。

couplemaker = function(A){couple$boyfriend[which.max(couple$goodfeeling*(couple$boyfriend %in% A))]} 

這段代碼選擇了一個有着最好的感覺但沒有與女朋友對應的男朋友。

爲了使我的目的更清晰,這些是我打算製作的理想套件。

Paris = 'Sue (Peter|Sam|Chris)' 
US = 'Lora (Peter|Chris|Sam)' 

Paris 
[1] 'Sue (Sam)' 
US 
[1] 'Lora (Peter)' 

回答

1

這會是一個足夠的解決方法嗎? group_by女朋友,然後獲得最佳的對,然後paste

library(dplyr) 
do.call(paste,couple %>% group_by(girlfriend) %>% 
         summarise(boyfriend[which.max(goodfeeling)]) 
) 

library(data.table) 
do.call(paste, couple[, boyfriend[which.max(goodfeeling)], by = .(girlfriend)]) 

# [1] "Julie John" "Lora Peter" "Sue Sam" 
+1

那麼,我的目標是做的是在一個字符串中刪除不太有希望的候選人。 – Rcoding

+0

@編碼是的,但這也是其他方式正確嗎? Ryt! –

+0

Ryt!輝煌的方式來分組夫婦雖然。 – Rcoding

相關問題