How to apply different function to grouping values in an R data frame?


To apply different function to grouping values in an R data frame, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use ifelse function to apply different function to grouping values.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-sample(1:50,25)
Grp<-sample(LETTERS[1:4],25,replace=TRUE)
df<-data.frame(x,Grp)
df

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

  x Grp
1 28 B
2 50 B
3 42 D
4 7 A
5 37 D
6 15 D
7 13 B
8 20 C
9 33 B
10 23 C
11 41 A
12 36 B
13 1 A
14 29 C
15 46 D
16 19 C
17 47 D
18 31 A
19 30 A
20 48 A
21 27 B
22 22 D
23 32 C
24 9 A
25 39 D

Apply different function to grouping values

Use if else function to apply different function to grouping values in Grp column of data frame df −

x<-sample(1:50,25)
Grp<-sample(LETTERS[1:4],25,replace=TRUE)
df<-data.frame(x,Grp)
df$New_x<-
ifelse(df$Grp=="A",2+x,ifelse(df$Grp=="B",0.5*x,ifelse(df$Grp=="C",2*x,ifelse(df$Gr
p=="D",x-1,NA))))
df

Output

   x Grp New_x
1  28 B 14.0
2  50 B 25.0
3  42 D 41.0
4  7 A 9.0
5  37 D 36.0
6  15 D 14.0
7  13 B 6.5
8 20 C 40.0
9 33 B 16.5
10 23 C 46.0
11 41 A 43.0
12 36 B 18.0
13 1 A 3.0
14 29 C 58.0
15 46 D 45.0
16 19 C 38.0
17 47 D 46.0
18 31 A 33.0
19 30 A 32.0
20 48 A 50.0
21 27 B 13.5
22 22 D 21.0
23 32 C 64.0
24 9 A 11.0
25 39 D 38.0

Updated on: 13-Aug-2021

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements