How to find the range of columns if some columns are categorical in R data frame?


To find the range of columns 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 range of columns if some columns are categorical.

Example

Create the data frame

Let’s create a data frame as shown below −

Level<-sample(c("low","medium","high"),25,replace=TRUE)
Group<-sample(c("first","second"),25,replace=TRUE)
DV1<-rnorm(25)
DV2<-rnorm(25)
df<-data.frame(Level,Group,DV1,DV2)
df

Output

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

   Level  Group         DV1        DV2
1  low    first   0.4545623484  1.22457875
2  medium first   2.4889402150  1.32313305
3  high   second -0.3256057111 -0.16534155
4  high   first   0.2666232706  0.39905496
5  medium second  0.2505499602  0.16705061
6  medium second  1.4470741152 -0.95407901
7  medium second -0.6963398452 -1.63102625
8  low    second -0.3689070319  0.89160781
9  low    first   0.0205268260 -0.19421709
10 high   second -0.2771581159 -0.58141607
11 medium first   0.3217334614 -2.01628121
12 low    first  -1.0149160270 -1.58027196
13 high   second  0.2073933789  0.39786787
14 high   second -0.7404056228 -0.36160167
15 high   second  0.5608725981  0.13807999
16 medium second  0.1696982325 -2.17273629
17 medium first   0.3139221353  0.87757664
18 high   first   0.2133404248  0.73458995
19 medium first  -0.0001034651  0.32130203
20 medium second  1.2085469946  1.55984002
21 high   first   0.0703214269  0.04091434
22 low    first   0.2014678620 -0.96800566
23 low    first  -0.8416639293  0.96249702
24 low    first  -0.3355991743  1.63965559
25 low    first   0.2084838973 -2.09570685

Find the range if some columns are categorical

Using numcolwise function from plyr package to find the range of numerical columns if some columns are categorical in the data frame df −

Level<-sample(c("low","medium","high"),25,replace=TRUE)
Group<-sample(c("first","second"),25,replace=TRUE)
DV1<-rnorm(25)
DV2<-rnorm(25)
df<-data.frame(Level,Group,DV1,DV2)
library(plyr)
numcolwise(range)(df)

Output

      DV1      DV2
1 -1.014916 -2.172736
2  2.488940  1.639656

Updated on: 12-Nov-2021

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements