How to find the square root of each value in columns if some columns are categorical in R data frame?


To find the square root of each value in 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 square root of each value in 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<-sample(c(1,4,9,16,25,36,49,64,81,100),25,replace=TRUE)
DV2<-sample(c(1,4,9,16,25,36,49,64,81,100),25,replace=TRUE)
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  high   second  49  64
2  medium second  64  64
3  high   second  64   4
4  medium second  81  49
5  medium second   9  64
6  low    second  64   4
7  low    second  49  64
8  high   first  100  81
9  high   second  49   9
10 high   second  81   1
11 medium second  64  64
12 low    second  64   4
13 high   first    4  81
14 medium second 100   1
15 low    first   16  16
16 high   second  64  36
17 high   first   81  16
18 high   first   16   9
19 high   first   81   1
20 high   second 100  16
21 low    second  25   9
22 medium first   36  16
23 high   first  100  64
24 high   first   25  36
25 high   second   1  49

Find the square root of each value in columns if some columns are categorical

Using numcolwise function from plyr package to find the square root of each value in 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<-sample(c(1,4,9,16,25,36,49,64,81,100),25,replace=TRUE)
DV2<-sample(c(1,4,9,16,25,36,49,64,81,100),25,replace=TRUE)
df<-data.frame(Level,Group,DV1,DV2)
library(plyr)
numcolwise(sqrt)(df)

Output

   DV1 DV2
1   7  8
2   8  8
3   8  2
4   9  7
5   3  8
6   8  2
7   7  8
8  10  9
9   7  3
10  9  1
11  8  8
12  8  2
13  2  9
14 10  1
15  4  4
16  8  6
17  9  4
18  4  3
19  9  1
20 10  4
21  5  3
22  6  4
23 10  8
24  5  6
25  1  7

Updated on: 09-Nov-2021

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements