[英]How can I summarize this data with R?
我正在分析不同購物地點之間的客戶流。 我有這樣的數據:
df <- data.frame(customer.id=letters[seq(1,7)],
shop.1=c(1,1,1,1,1,0,0),
shop.2=c(0,0,1,1,1,1,0),
shop.3=c(1,0,0,0,0,0,1))
df
#> customer.id shop.1 shop.2 shop.3
#> 1 a 1 0 1
#> 2 b 1 0 0
#> 3 c 1 1 0
#> 4 d 1 1 0
#> 5 e 1 1 0
#> 6 f 0 1 0
#> 7 g 0 0 1
因此,例如:
客戶“ a”僅在1號和3號商店購物,
客戶“ b”僅在1號商店購物,
客戶“ c”僅在1號和2號商店購物,
我想像這樣總結數據:
#> shop.1 shop.2 shop.3
#> shop.1 5 3 1
#> shop.2 3 4 0
#> shop.3 1 0 2
因此,例如,第1行顯示為:
我該如何做到這一點(請注意:我的數據集中有很多商店,因此首選可擴展的方法)?
經過一些基本的操作后, crossprod
可以照顧您想要做的事情,將其分為代表customer
和shop
兩列:
tmp <- cbind(df[1],stack(df[-1]))
tmp <- tmp[tmp$values==1,]
crossprod(table(tmp[c(1,3)]))
# ind
#ind shop.1 shop.2 shop.3
# shop.1 5 3 1
# shop.2 3 4 0
# shop.3 1 0 2
您想將shop.*
的同時出現列表化shop.*
變量:
df[,2:4] <- sapply(df[,2:4], function(x) { ifelse(x=="", 0, 1) } )
1)可以使用ftable(xtabs(...))
來完成,但是我為此苦苦掙扎了很ftable(xtabs(...))
,無法理解。 我最接近的是:
> ftable(xtabs(~ shop.1 + shop.2 + shop.3, df))
shop.3 0 1
shop.1 shop.2
0 0 0 1
1 1 0
1 0 1 1
1 3 0
2)如@thelatemail所示,您還可以:
# Transform your df from wide-form to long-form...
library(dplyr)
library(reshape2)
occurrence_df <- reshape2::melt(df, id.vars='customer.id') %>%
dplyr::filter(value==1)
customer.id variable value
1 a shop.1 1
2 b shop.1 1
3 c shop.1 1
4 d shop.1 1
5 e shop.1 1
6 c shop.2 1
7 d shop.2 1
8 e shop.2 1
9 f shop.2 1
10 a shop.3 1
11 g shop.3 1
確實,我們可以將value
列放在過濾器之后,因此我們可以通過管道%>% select(-value)
customer.id variable
1 a shop.1
2 b shop.1
3 c shop.1
4 d shop.1
5 e shop.1
6 c shop.2
7 d shop.2
8 e shop.2
9 f shop.2
10 a shop.3
11 g shop.3
#然后執行與@thelatemail的答案相同的crossprod步驟:
crossprod(table(occurrence_df))
variable
variable shop.1 shop.2 shop.3
shop.1 5 3 1
shop.2 3 4 0
shop.3 1 0 2
(腳注:
read.csv
,請使用read.csv
參數stringsAsFactors=TRUE
使其成為因子,或者使用colClasses
使其成為數字,並查看所有重復的問題。) 實際上,矩陣運算似乎足夠了,因為數據幀只有0
和1
。
首先,排除customer.id
列,然后將data.frame
更改為matrix
。 這可能很容易。 ( mydf
是數據框的名稱。)
# base R way
as.matrix(mydf[,-1])
#> shop.1 shop.2 shop.3
#> [1,] 1 0 1
#> [2,] 1 0 0
#> [3,] 1 1 0
#> [4,] 1 1 0
#> [5,] 1 1 0
#> [6,] 0 1 0
#> [7,] 0 0 1
library(dplyr) #dplyr way
(mymat <-
mydf %>%
select(-customer.id) %>%
as.matrix())
#> shop.1 shop.2 shop.3
#> [1,] 1 0 1
#> [2,] 1 0 0
#> [3,] 1 1 0
#> [4,] 1 1 0
#> [5,] 1 1 0
#> [6,] 0 1 0
#> [7,] 0 0 1
使用此矩陣,只需執行以下矩陣操作即可 。
t(mymat) %*% mymat
#> shop.1 shop.2 shop.3
#> shop.1 5 3 1
#> shop.2 3 4 0
#> shop.3 1 0 2
您可以得到答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.