有没有办法将paste0函数与列表组合?

问题描述 投票:0回答:1

我有一个名字向量:

names <- c("a", "b", "c", "d", "e", "f", "g", "h")

我想分别将这些名称与这些数字进行一系列组合:

numbers <- c(0, 0:2, 0:3, 0:1, 0:1, 0, 0, 0)

所以我的组合是:

a0 b0 b1 b2 c0 c1 c2 c3 d0 d1 e0 e1 f0 g0 h0

我该怎么做?我宁愿使用向量化函数而不是迭代。

我尝试了这些代码,但得到了错误的结果(可能是由于回收或其他原因):

paste0(names, numbers, recycle0 = F)
paste0(names, numbers, recycle0 = T)
paste0(names, numbers |> as.list())
purrr::map_chr(names, paste0(c(0, 0:2, 0:3, 0:1, 0:1, 0, 0, 0)))

还有一些我记不太清楚了。

谢谢你

r loops iteration
1个回答
0
投票

这里使用

numbers
作为具有最大序列的向量的解决方案

names <- c("a", "b", "c", "d", "e", "f", "g", "h")

numbers <- c(0, 2, 3, 1, 1, 0, 0, 0)

library(purrr)

unlist(map2(.x = names,.y = numbers,.f = \(.x,.y) paste0(.x,0:.y)))

[1] "a0" "b0" "b1" "b2" "c0" "c1" "c2" "c3" "d0" "d1" "e0" "e1" "f0" "g0" "h0"
© www.soinside.com 2019 - 2024. All rights reserved.