Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a contingency table where one variable is categorized based on given breaks

Tags:

r

Given a data.frame like the following

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

I want to create a contingency table where the values of Mount are categorized into intervals based on a vector B=c(0,100,500,1000,2000,3000,4000,5000). The result would be a table like this:

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

I was trying a data.table solution but was not able to get this result. How can I make this table or is possible to add extra option when calling table() function to get this result?

like image 507
Duck Avatar asked Jan 02 '26 08:01

Duck


1 Answers

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
like image 145
Roland Avatar answered Jan 04 '26 04:01

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!