Praveen M Kulkarni
Praveen M Kulkarni

Reputation: 57

R - put space at word begins with capital letter, for full column

i am having a column from XLSX imported to R, where each row is having a sentence without space, but words begins with Capital letters. tried to use

gsub("([[:upper:]])([[:upper:]][[:lower:]])", "\\1 \\2", x)

but this is working, if i start converting each row,

Example

1 HowDoYouWorkOnThis
2 ThisIsGreatExample
3 ProgrammingIsGood

Expected is

1 How Do You Work On This
2 This Is Great Example
3 Programming Is Good 

Upvotes: 0

Views: 118

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50688

Is this what you're after?

s <- c("HowDoYouWorkOnThis", "ThisIsGreatExample", "ProgrammingIsGood");

sapply(s, function(x) trimws(gsub("([A-Z])", " \\1", x)))
#       HowDoYouWorkOnThis        ThisIsGreatExample         ProgrammingIsGood
#"How Do You Work On This"   "This Is Great Example"     "Programming Is Good"

Or using stringr::str_replace_all:

library(stringr);
trimws(str_replace_all(s, "([A-Z])", " \\1"));
#[1] "How Do You Work On This" "This Is Great Example"
#[3] "Programming Is Good"

Upvotes: 2

Related Questions