- 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 create a new column for factor variable with changed factor levels by using mutate of dplyr package in R?
We know that a factor variable has many levels but it might be possible that the factor levels we have are not in the form as needed. For example, if we want to have capital letters as a factor level but the original data has small letters of English alphabets. In this situation we can convert those factor levels by using mutate of dplyr package.
Example
Consider the below data frame −
x <-letters[1:20] y <-20:1 df <-data.frame(x,y) str(df) 'data.frame': 20 obs. of 2 variables: $ x: Factor w/ 20 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ... $ y: int 20 19 18 17 16 15 14 13 12 11 ... df
Output
x y 1 a 20 2 b 19 3 c 18 4 d 17 5 e 16 6 f 15 7 g 14 8 h 13 9 i 12 10 j 11 11 k 10 12 l 9 13 m 8 14 n 7 15 o 6 16 p 5 17 q 4 18 r 3 19 s 2 20 t 1
Creating a new column with changed levels −
Example
df%>% mutate(x,levels=LETTERS[1:20])
Output
x y levels 1 a 20 A 2 b 19 B 3 c 18 C 4 d 17 D 5 e 16 E 6 f 15 F 7 g 14 G 8 h 13 H 9 i 12 I 10 j 11 J 11 k 10 K 12 l 9 L 13 m 8 M 14 n 7 N 15 o 6 O 16 p 5 P 17 q 4 Q 18 r 3 R 19 s 2 S 20 t 1 T
Lets’ have a look at another example −
F <-rep(c("Cold","Hot","Sweet","Bitter"),times=5) Count <-sample(1:50,20) Taste <-data.frame(F,Count) Taste
Output
F Count 1 Cold 49 2 Hot 18 3 Sweet 28 4 Bitter 9 5 Cold 29 6 Hot 13 7 Sweet 39 8 Bitter 30 9 Cold 11 10 Hot 5 11 Sweet 45 12 Bitter 31 13 Cold 36 14 Hot 41 15 Sweet 44 16 Bitter 15 17 Cold 20 18 Hot 48 19 Sweet 8 20 Bitter 43
Example
Taste%>% mutate(F,levels=rep(c("Very Cold","Very Hot","Very Sweet","Very Bitter"),times=5))
Output
F Count levels 1 Cold 49 Very Cold 2 Hot 18 Very Hot 3 Sweet 28 Very Sweet 4 Bitter 9 Very Bitter 5 Cold 29 Very Cold 6 Hot 13 Very Hot 7 Sweet 39 Very Sweet 8 Bitter 30 Very Bitter 9 Cold 11 Very Cold 10 Hot 5 Very Hot 11 Sweet 45 Very Sweet 12 Bitter 31 Very Bitter 13 Cold 36 Very Cold 14 Hot 41 Very Hot 15 Sweet 44 Very Sweet 16 Bitter 15 Very Bitter 17 Cold 20 Very Cold 18 Hot 48 Very Hot 19 Sweet 8 Very Sweet 20 Bitter 43 Very Bitter
Advertisements