How to convert a data frame into table for two factor columns and one numeric column in R?

R ProgrammingServer Side ProgrammingProgramming

When we have two factor columns and one numeric column then we can create a contingency table for the total count of numeric values based on the factor columns. This can be done with the help of xtabs function in base R. For example, if we have a data frame called df that contains two factor columns say f1 and f2, and one numeric column say Y then the contingency table for df can be created by using the command xtabs(Y~f1+f1,df).

Example1

Consider the below data frame −

Live Demo

> x1<-sample(LETTERS[1:4],20,replace=TRUE)
> x2<-sample(letters[1:4],20,replace=TRUE)
> y1<-rpois(20,5)
> df1<-data.frame(x1,x2,y1)
> df1

Output

   x1 x2 y1
1  B  a  5
2  B  c  6
3  D  b  3
4  D  c  5
5  C  b  8
6  D  c  4
7  B  c  8
8  A  a  3
9  D  c  6
10 D  d  2
11 D  c  9
12 D  c  5
13 C  d  8
14 C  d  6
15 D  d  4
16 C  c  4
17 D  d  5
18 A  c  2
19 A  c  4
20 B  d  5

Creating contingency table for data in df1 −

> xtabs(y1~x1+x2,df1)
x2

Output

x1 a b c  d
A  3 0 6  0
B  5 0 14 5
C  0 8 4  14
D  0 3 29 11

Example2

Live Demo

> var1<-sample(c("G1","G2","G3","G4"),20,replace=TRUE)
> var2<-sample(c("C1","C2","C3","C4"),20,replace=TRUE)
> Response<-rpois(20,2)
> df2<-data.frame(var1,var2,Response)
> df2

Output

   var1 var2 Response
1  G3   C2    1
2  G2   C4    4
3  G4   C2    3
4  G2   C3    4
5  G3   C4    1
6  G3   C3    1
7  G4   C1    1
8  G1   C4    3
9  G2   C3    1
10 G2   C1    0
11 G3   C1    1
12 G3   C4    0
13 G1   C1    2
14 G3   C1    1
15 G4   C1    3
16 G1   C2    4
17 G2   C4    2
18 G4   C4    4
19 G2   C4    1
20 G3   C3    0

Creating contingency table for data in df2 −

> xtabs(Response~var1+var2,df2)

Output

var2
var1 C1 C2 C3 C4
G1   2  4  0  3
G2   0  0  5  7
G3   2  1  1  1
G4   4  3  0  4
raja
Published on 04-Mar-2021 07:38:15
Advertisements