R语言 如何在一行中录入重复值

wf82jlnq  于 2023-01-28  发布在  其他
关注(0)|答案(3)|浏览(262)

请原谅我问了这么愚蠢的问题。
如果我想构建一个try,如下所示:2 × 1 m1n1x、“试1”、n-1 × 1 m2n1x、“试2”、n-1 × 1 m3n1x,其中nLevel中的元素数。

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

它是一种像2"", "Try1", (length(level)-1)"", "Try2", (length(level)-1)""那样构建try的方法吗?

5n0oy7gb

5n0oy7gb1#

我们可以使用

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" ""     ""     ""
0wi1tuuw

0wi1tuuw2#

你可以这样做:

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

用法:
x一个一个一个一个x一个一个二个一个x一个一个三个一个

wvmv3b1j

wvmv3b1j3#

假设您想要的不仅仅是“Try1”和“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)
)

相关问题