- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Articles
- How to apply a manually created function to two columns in an R data frame?
- How to subset an R data frame if one of the supplied grouping values is found?
- How to remove rows from an R data frame based on frequency of values in grouping column?
- How to convert negative values in an R data frame to positive values?
- How to convert empty values to NA in an R data frame?
- How to convert NaN values to NA in an R data frame?
- How to select positive values in an R data frame column?
- How to randomly replace values in an R data frame column?
- How to make all values in an R data frame unique?
- How to apply t test on each row of an R data frame?
- How to apply multiple AND conditions to a data frame in R?
- How to replace NA values with zeros in an R data frame?
- How to merge rows having same values in an R data frame?
- How to change row values based on column values in an R data frame?
- How to fill NA values with previous values in an R data frame column?

Advertisements