2015-09-06 63 views
0

我想組不同主題和不同的用戶數據幀生成的該主題在每個用戶的相對重要性的表格,如我的數據幀是分組多個變量 - R的

Topic User 
A  U1 
A  U2 
B  U2 
A  U1 
B  U1 
A  U1 

而且我想把它降低到

Topic User Importance 
A  U1 0.75 
A  U2 0.25 
B  U1 0.5 
B  U2 0.5 

有人可以指點我如何使用R,最好是dplyr嗎?處理這種

回答

5

這裏有一個快速data.table替代方法

library(data.table) 
setDT(df)[, as.data.table(table(User)/.N), by = Topic] 
# Topic User N 
# 1:  A U1 0.75 
# 2:  A U2 0.25 
# 3:  B U1 0.50 
# 4:  B U2 0.50 

這基本上是按組運行table(User)並按組分大小.N


或者simiarly與dplyr

df %>% 
    group_by(Topic) %>% 
    do(data.frame(table(.$User)/length(.$User))) 

# Source: local data frame [4 x 3] 
# Groups: Topic [2] 
# 
# Topic Var1 Freq 
# (fctr) (fctr) (dbl) 
# 1  A  U1 0.75 
# 2  A  U2 0.25 
# 3  B  U1 0.50 
# 4  B  U2 0.50 
3

一種方式是按主題/主題的用戶分別計數並加入結果:

topic_count <- df %>% group_by(Topic) %>% summarise(total=n()) 
user_count <- df %>% group_by(Topic, User) %>% summarise(cnt=n()) 

user_count %>% 
    left_join(topic_count, by="Topic") %>% 
    mutate(Importance=cnt/total) %>% 
    select(-cnt, -total) # Drop obsolete columns 

## Topic User Importance 
## 1 A  U1  0.75 
## 2 A  U2  0.25 
## 3 B  U1  0.50 
## 4 B  U2  0.50 
3

還有一種方法:

as.data.frame(prop.table(table(DF), margin = 1)) 
# Topic User Freq 
#1  A U1 0.75 
#2  B U1 0.50 
#3  A U2 0.25 
#4  B U2 0.50 
+0

是的,這是已經發布和刪除通過@RichardScrinven出於某種原因 –

+0

@DavidArenburg對不起,不知道;理查德取消刪除,我會刪除我的 –

+0

是的,我知道,你沒有足夠的代表來看到這個(即使在你的令人敬畏的答案後我的問題;))。我要求他退回,但他沒有迴應。 –