user3697665
user3697665

Reputation: 307

What is an elegant way to clean this character vector?

a = c("\r\n            sql r sqldf \r\n        ", 
      "\r\n            r sample \r\n        ",
      "\r\n            r \r\n        ")

The result I want is

[1] "sql; r; sqldf"
[2] "r; sample"
[3] "r"

I have used multiple calls to strsplit() and an sapply() loop to obtain the result I want, but it takes me about 7 lines to code. I am wondering if there could be a more elegant way to do this?

Upvotes: 1

Views: 447

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

You could use a combination of trimws() and gsub().

gsub(" ", "; ", trimws(a))
# [1] "sql; r; sqldf" "r; sample"     "r"    

Upvotes: 8

Related Questions