2017-06-14 31 views
1

我有一對數據框,其中有一對個人評分自己(1,0)並對他們的合作伙伴評分(1,0)。匹配配對數據的行之間的數據

have <- data.frame(group=c(1, 1, 2, 2, 3, 3), 
        person=c(1, 2, 1, 2, 1, 2), 
        rateSelf=c(1, 0, 1, 0, 1, 0), 
        rateOther=c(1, 1, 1, 0, 0, 0)) 
have 

# group person rateSelf rateOther 
#1  1  1  1   1 
#2  1  2  0   1 
#3  2  1  1   1 
#4  2  2  0   0 
#5  3  1  1   0 
#6  3  2  0   0 

我想比較人如何評價自己(rateSelf)他們是如何被其他人(ratedByOther)評級。

want <- data.frame(group=c(1, 1, 2, 2, 3, 3), 
        person=c(1, 2, 1, 2, 1, 2), 
        rateSelf=c(1, 0, 1, 0, 1, 0), 
        rateOther=c(1, 1, 1, 0, 0, 0), 
        ratedByOther=c(1, 1, 0, 1, 0, 0)) 
want 

# group person rateSelf rateOther ratedByOther 
#1  1  1  1   1   1 
#2  1  2  0   1   1 
#3  2  1  1   1   0 
#4  2  2  0   0   1 
#5  3  1  1   0   0 
#6  3  2  0   0   0 

什麼是一個聰明的方式來獲得ratedByOther

+1

目前尚不清楚有關獲取的邏輯'ratedByOther' – akrun

+0

比方說,我' (2)中的人1,你在'group'中是'2人'。我評價自己('have [3,3] == 1')並評價你('have [3,4] == 1')。我想比較我如何評價自己(1)和評價我的方式('have [4,4] == 0')。我需要在我的排名中得到你的評價。 –

+0

'have $ rateByOther < - with(have,ave(rateOther,group,FUN = rev))' – alistaire

回答

1

認爲這你想要做什麼:

library(dplyr) 
want <- have %>% 
    group_by(group) %>% 
    mutate(ratedByOther = rev(rateOther)) 

    group person rateSelf rateOther ratedByOther 
    <dbl> <dbl> <dbl>  <dbl>  <dbl> 
1  1  1  1   1   1 
2  1  2  0   1   1 
3  2  1  1   1   0 
4  2  2  0   0   1 
5  3  1  1   0   0 
6  3  2  0   0   0 
+0

'rev()'來拯救。太好了! –

0

我們可以使用data.table

library(data.table) 
setDT(have)[, ratedByOther := rev(rateOther), group] 
相關問題