
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Single Quote from String Column in R Data Frame
Sometimes column values in an R data frame have single quote associated with them and to perform the analysis we need to remove that quote. Therefore, to remove single quote from string column, we can use gsub function by defining the single quote and replacing it with blank(not space) as shown in the below examples.
Consider the below data frame −
Example
x1<-sample(c("India'","Sudan'","Croatia'"),20,replace=TRUE) x2<-rpois(20,5) df1<-data.frame(x1,x2) df1
Output
x1 x2 1 India' 6 2 Sudan' 3 3 Croatia' 9 4 Croatia' 3 5 Sudan' 4 6 Croatia' 4 7 India' 4 8 Croatia' 6 9 India' 4 10 Croatia' 7 11 Sudan' 8 12 India' 3 13 Croatia' 4 14 Sudan' 6 15 Sudan' 3 16 India' 11 17 Croatia' 8 18 Sudan' 6 19 Sudan' 10 20 Sudan' 5
Removing ' from column x1 in df1 −
Example
df1$x1<-gsub("'","",df1$x1) df1
Output
x1 x2 1 India 6 2 Sudan 3 3 Croatia 9 4 Croatia 3 5 Sudan 4 6 Croatia 4 7 India 4 8 Croatia 6 9 India 4 10 Croatia 7 11 Sudan 8 12 India 3 13 Croatia 4 14 Sudan 6 15 Sudan 3 16 India 11 17 Croatia 8 18 Sudan 6 19 Sudan 10 20 Sudan 5
Example
y1<-sample(c("'A'","'B'","'C'"),20,replace=TRUE) y2<-rnorm(20,1) df2<-data.frame(y1,y2) df2
Output
y1 y2 1 'B' 0.49282668 2 'B' -0.90061585 3 'B' 0.89346759 4 'A' 1.96469552 5 'A' 1.21931750 6 'A' 0.32022463 7 'A' 0.97912117 8 'B' 1.38781374 9 'C' -0.69066318 10 'B' 1.45014864 11 'C' 1.61876980 12 'C' 1.69046763 13 'C' -0.08073507 14 'B' 1.73212908 15 'C' 0.85473489 16 'B' -0.24975030 17 'A' 0.40313471 18 'B' 0.60537047 19 'B' 0.30200882 20 'C' 2.29497113
Removing ' from column y1 in df2 −
Example
df2$y1<-gsub("'","",df2$y1) df2
Output
y1 y2 1 B 0.49282668 2 B -0.90061585 3 B 0.89346759 4 A 1.96469552 5 A 1.21931750 6 A 0.32022463 7 A 0.97912117 8 B 1.38781374 9 C -0.69066318 10 B 1.45014864 11 C 1.61876980 12 C 1.69046763 13 C -0.08073507 14 B 1.73212908 15 C 0.85473489 16 B -0.24975030 17 A 0.40313471 18 B 0.60537047 19 B 0.30200882 20 C 2.29497113
Advertisements