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

R ProgrammingServer Side ProgrammingProgramming

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

Example

Create the data frame

Let’s create a data frame as shown below −

Gender<-sample(c("Male","Female"),25,replace=TRUE)
Salary<-sample(10000:50000,25)
Experience<-sample(1:10,25,replace=TRUE)
df<-data.frame(Gender,Salary,Experience)
df

Output

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

   Gender   Salary Experience
1  Female  31830     3
2  Male    19778     2
3  Female  42307     9
4  Female  11013     3
5  Male    48208     3
6  Male    40936    10
7  Male    21131     1
8  Male    39166     9
9  Male    36098     2
10 Male    40579     4
11 Male    12884     8
12 Female  15205     6
13 Female  17143     9
14 Female  12945     9
15 Female  21179    10
16 Male    30318     5
17 Male    29230     6
18 Female  26574     9
19 Male    49227     5
20 Male    44086     9
21 Male    47451     4
22 Female  49371     5
23 Female  14601    10
24 Female  43574     4
25 Male    36308     6

Find the cumulative sums if some columns are categorical

Using numcolwise function from plyr package to find the cumulative of numerical columns in the data frame df −

Gender<-sample(c("Male","Female"),25,replace=TRUE)
Salary<-sample(10000:50000,25)
Experience<-sample(1:10,25,replace=TRUE)
df<-data.frame(Gender,Salary,Experience)
library(plyr)
numcolwise(cumsum)(df)

Output

   Salary Experience
1   43316   9
2   59418  18
3   70463  24
4  112002  32
5  129669  41
6  143625  50
7  168626  55
8  181440  65
9  213943  75
10 235701  84
11 275620  93
12 302459  94
13 326787 102
14 372124 108
15 414284 115
16 453324 123
17 501014 131
18 514031 134
19 543122 138
20 589538 141
21 622802 142
22 651796 150
23 668540 157
24 701131 162
25 735165 165
raja
Published on 10-Nov-2021 06:04:29
Advertisements