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

R ProgrammingServer Side ProgrammingProgramming

To find the cosine 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 cosine 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(1:5,25,replace=TRUE)
DV2<-sample(1:5,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  medium  first  3    3
2  medium  second 5    3
3  low     first  5    4
4  low     second 4    3
5  medium  first  1    3
6  medium  first  2    1
7  medium  second 3    5
8  low     second 4    1
9  low     second 2    1
10 medium  first  1    5
11 high    first  2    4
12 medium  second 5    1
13 medium  second 5    1
14 high    first  5    3
15 low     first  2    5
16 high    first  1    1
17 low     second 4    2
18 high    second 1    5
19 medium  second 3    2
20 medium  second 1    2
21 high    second 5    2
22 medium  second 1    4
23 low     second 3    1
24 medium  first  5    5
25 low     first  5    1

Find the cosine of each value in columns if some columns are categorical

Using numcolwise function from plyr package to find the cosine 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(1:5,25,replace=TRUE)
DV2<-sample(1:5,25,replace=TRUE)
df<-data.frame(Level,Group,DV1,DV2)
library(plyr)
numcolwise(cos)(df)

Output

      DV1        DV2
1   0.5403023  -0.4161468
2  -0.4161468   0.2836622
3   0.2836622  -0.4161468
4  -0.6536436  -0.9899925
5   0.5403023   0.5403023
6  -0.9899925  -0.9899925
7  -0.6536436   0.5403023
8   0.2836622  -0.4161468
9   0.2836622   0.5403023
10 -0.4161468   0.5403023
11 -0.9899925  -0.6536436
12  0.5403023  -0.9899925
13 -0.4161468  -0.4161468
14  0.2836622   0.2836622
15  0.2836622  -0.4161468
16  0.2836622  -0.9899925
17 -0.9899925  -0.4161468
18 -0.9899925   0.2836622
19  0.2836622   0.2836622
20 -0.6536436  -0.9899925
21 -0.6536436   0.5403023
22 -0.9899925   0.2836622
23 -0.4161468  -0.9899925
24  0.2836622   0.2836622
25 -0.6536436  -0.4161468
raja
Published on 08-Nov-2021 11:55:33

Advertisements