Home > Software engineering >  How to entry repeated value in a row
How to entry repeated value in a row

Time:01-28

Please pardon me for such silly question.

If I want to build a try as this: 2 "", "Try1", n-1 "", "Try2", n-1 "", which n is number of elements in Level.


level <- c("L1", "L2", "L3", "L4")
try<- t(c("","", "Try1" ,"","","", "Try2","","", ""))

Is it a way to build try in a way like 2"", "Try1", (length(level)-1)"", "Try2", (length(level)-1)""?

CodePudding user response:

We may use

n <- length(Level) - 1
tail(na.omit(c(mapply(`c`, replicate(n, rep("", n), 
   simplify = FALSE), c(paste0("Try", 1:2), NA)))), -1)
[1] ""     ""     "Try1" ""     ""     ""     "Try2" ""     ""     ""    

CodePudding user response:

You can do something like this:

generate_try <- function(n) {
  t(c("","", unlist(lapply((n-1):2, \(i) c(paste0("Try", n-i),rep("", i)))),""))
} 

Usage:

generate_try(4)
     [,1] [,2] [,3]   [,4] [,5] [,6] [,7]   [,8] [,9] [,10]
[1,] ""   ""   "Try1" ""   ""   ""   "Try2" ""   ""   ""   
generate_try(10)
     [,1] [,2] [,3]   [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13]  [,14] [,15] [,16]
[1,] ""   ""   "Try1" ""   ""   ""   ""   ""   ""   ""    ""    ""    "Try2" ""    ""    ""   
     [,17] [,18] [,19] [,20] [,21] [,22]  [,23] [,24] [,25] [,26] [,27] [,28] [,29] [,30]  [,31]
[1,] ""    ""    ""    ""    ""    "Try3" ""    ""    ""    ""    ""    ""    ""    "Try4" ""   
     [,32] [,33] [,34] [,35] [,36] [,37]  [,38] [,39] [,40] [,41] [,42] [,43]  [,44] [,45] [,46]
[1,] ""    ""    ""    ""    ""    "Try5" ""    ""    ""    ""    ""    "Try6" ""    ""    ""   
     [,47] [,48]  [,49] [,50] [,51] [,52]  [,53] [,54] [,55]
[1,] ""    "Try7" ""    ""    ""    "Try8" ""    ""    ""   
generate_try(length(Level))
     [,1] [,2] [,3]   [,4] [,5] [,6] [,7]   [,8] [,9] [,10]
[1,] ""   ""   "Try1" ""   ""   ""   "Try2" ""   ""   ""   

CodePudding user response:

Assuming you might want more than just 'Try1' and 'Try2'

Level <- c("L1", "L2", "L3", "L4")

tryCt <- 2

try <- c(
  "", "",
  paste0("Try", seq(tryCt)) |> 
    purrr::map(~c(.x, rep("", length(Level) - 1))) |> 
    purrr::reduce(c)
)
  •  Tags:  
  • r
  • Related