最佳方法以编程方式扩展和重新排序R中的数组?

huangapple go评论65阅读模式
英文:

Best way to programatically extend and re-order array in R?

问题

使用paste函数可以得到cols3,而不需要使用循环。以下是代码示例:

cols3 <- paste(cols1, cols2)
cols3

这将生成与所需cols3相同的输出。

英文:

Very simple R question:

What simplest operation should I use with cols1 and cols2 to obtain cols3 below?
(using loop is not the answer)

&gt;   cols1 &lt;-  paste0(letters[1:3]);cols1
[1] &quot;a&quot; &quot;b&quot; &quot;c&quot;
&gt;   cols2 &lt;- paste0(cols1, &quot;.new&quot;); cols2
[1] &quot;a.new&quot; &quot;b.new&quot; &quot;c.new&quot;
&gt;   cols3 =  c(&quot;a&quot;, &quot;a.new&quot; , &quot;b&quot; ,&quot;b.new&quot; , &quot;c&quot;, &quot;c.new&quot;); cols3
[1] &quot;a&quot;     &quot;a.new&quot; &quot;b&quot;     &quot;b.new&quot; &quot;c&quot;     &quot;c.new&quot;


</details>


# 答案1
**得分**: 3

使用`c` + `rbind`:
```r
c(rbind(cols1, cols2))
#[1] "a"     "a.new" "b"     "b.new" "c"     "c.new"

FYI,这有时被称为“交错”或“交织”。还有内置的vctrs::vec_interleave

vctrs::vec_interleave(cols1, cols2)
#[1] "a"     "a.new" "b"     "b.new" "c"     "c.new"
英文:

With c + rbind

c(rbind(cols1, cols2))
#[1] &quot;a&quot;     &quot;a.new&quot; &quot;b&quot;     &quot;b.new&quot; &quot;c&quot;     &quot;c.new&quot;

FYI, this is sometimes called "interleaving", or "interlacing".
There is also the built-in vctrs::vec_interleave:

vctrs::vec_interleave(cols1, cols2)
#[1] &quot;a&quot;     &quot;a.new&quot; &quot;b&quot;     &quot;b.new&quot; &quot;c&quot;     &quot;c.new&quot;

huangapple
  • 本文由 发表于 2023年2月6日 21:32:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定