Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a sequential character vector without a loop?

Tags:

r

I'm trying to generate a character vector that includes a sequence of n numbers (as character) with m empty string elements in between each number element.

I managed to generate the vector using a loop. Is there a way to implement this more conciseley without a loop, and would this be more efficient?

sequence = character(0)
n = 3
m = 2

for(i in 1:n){
  sequence <- c(sequence, rep("",m), i)
  i <- i + 1
}

The output is a vector like:

c("","","1","","","2","","","3")
like image 877
MMWeb Avatar asked Apr 16 '26 03:04

MMWeb


2 Answers

Here is another way to with rep and lapply.

seq_fun <- function(n, m){
  unlist(lapply(1:n, function(x) c(rep("", times = m), x)))
}

seq_fun(3, 2)
# [1] ""  ""  "1" ""  ""  "2" ""  ""  "3"
like image 84
www Avatar answered Apr 18 '26 15:04

www


1) Create an m by n matrix of "" and rbind 1:n to the bottom of it. Then unravel that into a vector:

c(rbind(matrix("", m, n), 1:n))
## [1] ""  ""  "1" ""  ""  "2" ""  ""  "3"

2) Another approach is to create an m1*n long vector of "" and replace positions m1*(1:n) with 1:n.

m1 <- m + 1
replace(character(m1 * n), m1 * (1:n), 1:n)
## [1] ""  ""  "1" ""  ""  "2" ""  ""  "3"

Alternately we could use a logical second argument:

replace(character(m1 * n), c(logical(m), TRUE), 1:n)
## [1] ""  ""  "1" ""  ""  "2" ""  ""  "3"
like image 35
G. Grothendieck Avatar answered Apr 18 '26 17:04

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!