# How to find the column median if some columns are categorical in R data frame?

To find the column median if some columns are categorical in R data frame, we can follow the below steps −

• First of all, create a data frame.

• Then, use numcolwise function from plyr package to find the column median if some columns are categorical.

## Example 1

#### Create the data frame

Let’s create a data frame as shown below −

Group<-sample(c("I","II","III","IV"),25,replace=TRUE)
Num1<-sample(1:50,25)
Num2<-sample(1:50,25)
df1<-data.frame(Group,Num1,Num2)
df1

## Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   Group Num1 Num2
1  III   46    25
2   I    41    39
3  III   4      1
4  IV   32     23
5  IV    2      7
6  III   7     15
7  II   44     48
8  IV   40      3
9  III  36     45
10 III  45     11
11 II   21     10
12 IV   23     47
13 I    12     35
14 III   3     42
15 IV   43     40
16 IV   19     14
17 IV   15      6
18 I    35     38
19 IV   18     34
20 II   20     44
21 III  30     17
22 IV   34     32
23 II   16     18
24 I    14      5
25 I    13     24

Find the column median if some columns are categorical

Using numcolwise function from plyr package to find the column median of numerical columns in the data frame df1 −

Group<-sample(c(“I”,”II”,”III”,”IV”),25,replace=TRUE)
Num1<-sample(1:50,25)
Num2<-sample(1:50,25)
df1<-data.frame(Group,Num1,Num2)
library(plyr)
numcolwise(median)(df1)

## Output

  Num1 Num2
1 30   28

## Example 2

#### Create the data frame

Let’s create a data frame as shown below −

Categories<-sample(c("First","Second","Third"),25,replace=TRUE)
Score<-sample(1:10,25,replace=TRUE)
Price<-sample(1:5,25,replace=TRUE)
df2<-data.frame(Categories,Score,Price)
df2

## Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   Categories Score Price
1  Second      4     3
2  First       2     2
3  Third       4     2
4  Second      2     4
5  Second      4     2
6  First       4     3
7  Third       3     5
8  Third       4     3
9  First       6     1
10 Third       4     1
11 First       5     3
12 Second      8     5
13 Third       4     1
14 Second      5     2
15 Second      6     5
16 Third       7     5
17 Third       6     2
18 Third       3     1
19 Second      1     4
20 Second      7     3
21 Second      4     2
22 Third       4     3
23 Second      1     5
24 First       6     2
25 First       4     3

Find the column median if some columns are categorical

Using numcolwise function from plyr package to find the column median of numerical columns in the data frame df2 −

Categories<-sample(c("First","Second","Third"),25,replace=TRUE)
Score<-sample(1:10,25,replace=TRUE)
Price<-sample(1:5,25,replace=TRUE)
df2<-data.frame(Categories,Score,Price)
library(plyr)
numcolwise(median)(df2)

## Output

   Score Price
1    6    4