简体   繁体   English

如何在 R 中连接两个 arrays

[英]How to concatenate two arrays in R

I have two arrays.我有两个 arrays。

Using numpy.append we can merge two arrays.使用numpy.append我们可以合并两个 arrays。

How can we do same thing in R?我们如何在 R 中做同样的事情?

merge can not do that. merge不能这样做。

Python Output/Example: Python 输出/示例:

   a=np.array([1,2,3,4,5,5])
   b=np.array([0,0,0,0,0,0])
   np.append(a,b)

   array([1, 2, 3, 4, 5, 5, 0, 0, 0, 0, 0, 0])   # this is what I want

x<-c(mat, (0.0) * (l - length(demeaned)))

mat is matrix (size is 20)

l - length(demeaned) is 10 l - length(demeaned)为 10

i want at the end 30 size我想要最后 30 码

Thec -function concatenates its arguments. c - 函数连接其 arguments。 A vector can be a concatenation of numbers or of other verctors:向量可以是数字或其他向量的串联:

a = c(1,2,3,4,5,5)
b = c(0,0,0,0,0,0)
c(a,b)

 [1] 1 2 3 4 5 5 0 0 0 0 0 0

At least for one-dimensional arrays like in your python-example this is equivalent to np.append至少对于一维 arrays 就像在你的 python 示例中,这相当于np.append

Adding to the previous answer, you can use rbind or cbind to create two-dimensional arrays (matrices) from simple arrays (vectors):添加到上一个答案,您可以使用rbindcbind从简单的 arrays (向量)创建二维 arrays (矩阵):

cbind(a,b)

# output
 a b
[1,] 1 0
[2,] 2 0
[3,] 3 0
[4,] 4 0
[5,] 5 0
[6,] 5 0

or或者

rbind(a,b)

# output
[,1] [,2] [,3] [,4] [,5] [,6]
a    1    2    3    4    5    5
b    0    0    0    0    0    0

If you want to convert it back to vector, use as.vector .如果要将其转换回矢量,请使用as.vector This这个

as.vector(rbind(a,b))

will give you a joined vector with alternating elements.会给你一个带有交替元素的连接向量。

Also, note that c can flatten lists if you use the recursive=TRUE argument:另外,请注意,如果您使用recursive=TRUE参数, c可以展平列表:

a <- list(1,list(1,2,list(3,4)))
b <- 10
c(a,b, recursive = TRUE)

# output
[1]  1  1  2  3  4 10

Finally, you can use rep to generate sequences of repeating numbers:最后,您可以使用rep生成重复数字的序列:

rep(0,10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM