我有以下結構的數據幀骨料R數據幀:數據透視表類似的結果集
ChannelId,AuthorId
1,32
28,2393293
2,32
2,32
1,2393293
31,3
3,32
5,4
2,5
我要的是
AuthorId,1,2,3,5,28,31
4,0,0,0,1,0,0
3,0,0,0,0,0,1
5,0,1,0,0,0,0
32,1,2,0,1,0,0
2393293,1,0,0,0,1,0
是否有辦法去做這個?
我有以下結構的數據幀骨料R數據幀:數據透視表類似的結果集
ChannelId,AuthorId
1,32
28,2393293
2,32
2,32
1,2393293
31,3
3,32
5,4
2,5
我要的是
AuthorId,1,2,3,5,28,31
4,0,0,0,1,0,0
3,0,0,0,0,0,1
5,0,1,0,0,0,0
32,1,2,0,1,0,0
2393293,1,0,0,0,1,0
是否有辦法去做這個?
xtabs功能可以與指定利潤率公式被稱爲:
xtabs(~ AuthorId+ChannelId, data=dat)
ChannelId
AuthorId 1 2 28 3 31 5
2393293 1 0 1 0 0 0
3 0 0 0 0 1 0
32 1 2 0 1 0 0
4 0 0 0 0 0 1
5 0 1 0 0 0 0
也許最簡單的方法是:t(table(df))
:
# ChannelId
#AuthorId 1 2 3 5 28 31
# 3 0 0 0 0 0 1
# 4 0 0 0 1 0 0
# 5 0 1 0 0 0 0
# 32 1 2 1 0 0 0
# 2393293 1 0 0 0 1 0
如果你想使用dplyr::count
你可以這樣做:
library(dplyr)
library(tidyr)
df %>%
count(AuthorId, ChannelId) %>%
spread(ChannelId, n, fill = 0)
其中給出:
#Source: local data frame [5 x 7]
#Groups: AuthorId [5]
#
# AuthorId 1 2 3 5 28 31
#* <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 3 0 0 0 0 0 1
#2 4 0 0 0 1 0 0
#3 5 0 1 0 0 0 0
#4 32 1 2 1 0 0 0
#5 2393293 1 0 0 0 1 0
不應該爲'%>%'加載至少一個'dplyr'或'tidyr'來工作嗎? – Sumedh
我們也可以使用dcast
從data.table
。將'data.frame'轉換爲'data.table'並使用dcast
,fun.aggregate
作爲length
。
library(data.table)
dcast(setDT(df1), AuthorId~ChannelId, length)
# AuthorId 1 2 3 5 28 31
#1: 3 0 0 0 0 0 1
#2: 4 0 0 0 1 0 0
#3: 5 0 1 0 0 0 0
#4: 32 1 2 1 0 0 0
#5: 2393293 1 0 0 0 1 0
您是否試過'?table' ..如在't(table(df))'中? –
@StevenBeaupré我沒有想法將ChannelId作爲頭部傳遞。我打了聚集,dplyr.count和數,但沒有運氣。 –