vicky
vicky

Reputation: 415

How to duplicate each characters in a string and how to insert $ in between each characters in a string

I want to duplicate each characters in R Studio

a <- c("abcd")

I want the result to be

"aabbccdd"

I tried

strrep(a, 2)

But it gives me "abcdabcd"

Another thing I'm trying to do is:

I want the result to be "a$b$c$d", inserting $ in between each characters

Can anyone help? the simpler the better.

Upvotes: 1

Views: 193

Answers (2)

d.b
d.b

Reputation: 32548

gsub

gsub("(.)", "\\1\\1", a)
#[1] "aabbccdd"

gsub("(.)", "\\1$", a)
#[1] "a$b$c$d$"

strsplit

sapply(strsplit(a, ""), function(x) paste(rep(x, each = 2), collapse = ""))
#[1] "aabbccdd"

sapply(strsplit(a, ""), function(x) paste(paste0(x, "$"), collapse = ""))
#[1] "a$b$c$d$"

substring

sapply(a, function(x)
    paste(rep(substring(x, sequence(nchar(x)), sequence(nchar(x))), each = 2), collapse = ""))
#      abcd 
#"aabbccdd" 

sapply(a, function(x)
    paste(paste0(substring(x, sequence(nchar(x)), sequence(nchar(x))), "$"), collapse = ""))
#      abcd 
#"a$b$c$d$" 

Upvotes: 2

Marco Sandri
Marco Sandri

Reputation: 24262

A different solution:

paste(unlist(lapply(1:nchar(a), function(k) rep(substr(a,k,k),2))), collapse="")
# [1] "aabbccdd"

paste(unlist(lapply(1:nchar(a), function(k) rep(substr(a,k,k),1))), collapse="$")
# [1] "a$b$c$d"

Upvotes: 1

Related Questions