3

给定一个如下的data.frame

ID  Card.Type  Mount
001   Basic    500
002   Basic    400
003   Basic    700
004   Basic    1000
005   Silver   1200
006   Silver   1300
007   Basic    800
008   Silver   1400
009   Gold     2500
0010  Gold     5000
0012  Gold     7000
0013  Gold     15000

我想创建一个列联表,其中的值Mount根据向量分类为区间B=c(0,100,500,1000,2000,3000,4000,5000)。结果将是这样的表:

Card.Type   0-100 101-500 501-1000 1001-2000 2001-3000 3001-4000 4001-5000 >5000
Basic         0       2      2         0          0        0         0       0
Silver        0       0      0         3          0        0         0       0
Gold          0       0      0         0          1        0         1       2

我正在尝试一个data.table解决方案,但无法得到这个结果。如何制作此表或在调用table()函数以获得此结果时添加额外选项?

4

1 回答 1

8
DF <- read.table(text="ID  Card.Type  Mount
001   Basic    500
002   Basic    400
003   Basic    700
004   Basic    1000
005   Silver   1200
006   Silver   1300
007   Basic    800
008   Silver   1400
009   Gold     2500
0010  Gold     5000
0012  Gold     7000
0013  Gold     15000",header=TRUE)

DF$inter <- cut(DF$Mount,c(-1,100,500,1000,2000,3000,4000,5000,Inf))
table(DF[,c(2,4)])

# Card.Type (-1,100] (100,500] (500,1e+03] (1e+03,2e+03] (2e+03,3e+03] (3e+03,4e+03] (4e+03,5e+03] (5e+03,Inf]
# Basic        0         2           3             0             0             0             0           0
# Gold         0         0           0             0             1             0             1           2
# Silver       0         0           0             3             0             0             0           0
于 2013-04-05T19:16:53.703 回答