Re: [問題] 條件機率矩陣

作者: celestialgod (天)   2016-06-18 08:38:58
※ 引述《mowgur (PINNNNN)》之銘言:
: [問題類型]:
: 程式諮詢(我想用R 做某件事情,但是我不知道要怎麼用R 寫出來)
:
: [軟體熟悉度]:
: 入門(寫過其他程式,只是對語法不熟悉)
: [問題敘述]:
: 我想把這樣的資料
: 交易編號 會員卡號 V1 V2 V3 V4
: 6557 1235 0 0 1 1
: 6558 1235 1 0 1 0
: 6559 1235 1 1 1 0
: .
: .
: .
: .
: .
: 變成條件機率矩陣
: V1 V2 V3 V4
: V1 .2 .5 .7
: V2 .4 .6
: V3 .1
: V4
: [程式範例]:
: 資料group是8個dataframe組合的list 每個dataframe有14欄 前2欄是id 希望能夠
: 輸出8個條件機率矩陣組成的list
: 以下是我的程式碼及錯誤訊息
: m <- 12
: f <- list(matrix(nrow = m, ncol = m))
: cp <- list(matrix(nrow = m, ncol = m))
: summation <- list(c())
: for(k in 1:length(group)){
: group[[k]] <- group[[k]][,-c(1,2)]
: summation <- apply(group[[k]],2,sum)
: for(i in 1:(m-1)) {
: for(j in (i+1):m){
: index <- (group[[k]][,i]==1 & group[[k]][,j]==1)
: f[[k]][i,j] <- length(group[[k]][index,1])
: cp[[k]][i,j] <- f[[k]][i,j]/summation[[k]][j]
: }
: }
: }
: Error in `*tmp*`[[k]] : subscript out of bounds
: [環境敘述]:
: Rx64 3.2.5
: [關鍵字]:
:
: 選擇性,也許未來有用
:
library(dplyr)
# data generation
numMemer <- sample(300:500, 8, TRUE)
df_list <- lapply(1:8, function(i){
data.frame(member_id = rep(1:numMemer[i],
sample(1:15, numMemer[i], TRUE))) %>%
mutate(trans_id = 1:nrow(.), V1 = rbinom(nrow(.), 1, 0.5),
V2 = rbinom(nrow(.), 1, 0.5), V3 = rbinom(nrow(.), 1, 0.5),
V4 = rbinom(nrow(.), 1, 0.5))
})
# calculation of conditional probability matrix
prob_list <- lapply(df_list, select, starts_with("V")) %>%
lapply(as.matrix) %>%
lapply(function(x){
t(x) %*% x %>% sweep(1, diag(.), '/')
})
%>%, mutate, select請參考簽名檔的magrittr跟dplyr部分
作者: mowgur (PINNNNN)   2016-06-29 22:13:00
推推推推推

Links booklink

Contact Us: admin [ a t ] ucptt.com