![](/img/trans.png)
[英]How do I order a vector by attribute "names" in R but keeping the first element constant?
[英]How do I add a vector to another holding the first vector constant?
在保持第一個向量不變的同時,如何在另一個向量之間添加一個向量? 例如,如果我有c(1, 2, 3) + 1
。 我會得到2、3、4。如果我想將其擴展為1、1和2,我該怎么做才能得到
2, 3, 4, 3, 4, 5
憑直覺,我想c(1, 2, 3) + c(1, 2)
但這不起作用。
將評論變成答案,我們可以使用@jogo顯示的outer
c(outer(1:3, 1:2, FUN='+'))
# [1] 2 3 4 3 4 5
另一個選擇是rep
f <- function(x, y) {
x + rep(y, each = length(x))
}
f(1:3, 1:2)
# [1] 2 3 4 3 4 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.