我正在分析不同购物场所之间的顾客流动情况。我有这样的数据:
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因此,例如:
我想总结一下如下的数据:
#> shop.1 shop.2 shop.3
#> shop.1 5 3 1
#> shop.2 3 4 0
#> shop.3 1 0 2 例如,第1行的内容如下:
我如何做到这一点(请注意:我的数据集中有很多商店,所以首选可伸缩的方法)?
发布于 2019-03-05 03:37:42
在进行了一些基本操作之后,crossprod可以处理您想要做的事情,将其分别放在代表customer和shop的2列中:
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发布于 2019-03-05 02:07:23
您想要表出与shop.*变量的共生关系(shop.*)变量:
df[,2:4] <- sapply(df[,2:4], function(x) { ifelse(x=="", 0, 1) } )( 1)据说可以用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 02)如@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(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使它们成为数字,并查看其中的所有重复问题。)发布于 2019-03-05 04:18:21
事实上,矩阵操作似乎足够了,因为数据帧只有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你可以得到答案。
https://stackoverflow.com/questions/54994318
复制相似问题