在R中将不同长度的向量矩阵组合在一起

在R中将不同长度的向量矩阵组合在一起,r,R,我有两个向量,a和b。它们的长度均为10。然后我将它们组合成c。还有另一个向量d,长度20。我在尝试将它们组合在一起时收到错误消息。我想知道是否有任何结构可以让我将不同长度的向量组合在一起 > a<-rep(6,10) > b<-rep(8,10) > c<-cbind(a,b) > d<-rep(10,20) > c > x<-cbind(c,d) Warning message: In cbind(c, d) :

我有两个向量,
a和b
。它们的长度均为
10
。然后我将它们组合成
c
。还有另一个向量
d
,长度
20
。我在尝试将它们组合在一起时收到错误消息。我想知道是否有任何结构可以让我将不同长度的向量组合在一起

> a<-rep(6,10)
> b<-rep(8,10)
> c<-cbind(a,b)
> d<-rep(10,20)
> c
> x<-cbind(c,d)
  Warning message:
  In cbind(c, d) :
  number of rows of result is not a multiple of vector length (arg 2)
>a b c d c

>这里的问题是你的
c
不是一个向量。这是一个矩阵:

a <- rep(6,10);
b <- rep(8,10);
c <- cbind(a,b);
c;
##       a b
##  [1,] 6 8
##  [2,] 6 8
##  [3,] 6 8
##  [4,] 6 8
##  [5,] 6 8
##  [6,] 6 8
##  [7,] 6 8
##  [8,] 6 8
##  [9,] 6 8
## [10,] 6 8
c(typeof(c),mode(c),class(c));
## [1] "double"  "numeric" "matrix"
出现警告消息的原因是,当矩阵的高度为10时,您将
d
创建为长度为20。
cbind()
在技术上仍然成功(带有警告),但只是将向量中的新列截断为与矩阵相同的高度:

d <- rep(10,20);
cbind(c,d);
##       a b  d
##  [1,] 6 8 10
##  [2,] 6 8 10
##  [3,] 6 8 10
##  [4,] 6 8 10
##  [5,] 6 8 10
##  [6,] 6 8 10
##  [7,] 6 8 10
##  [8,] 6 8 10
##  [9,] 6 8 10
## [10,] 6 8 10
## Warning message:
## In cbind(c, d) :
##   number of rows of result is not a multiple of vector length (arg 2)

d如果您只想组合两个长度不等的数值向量,请使用c()运算符:

a <- rep(6,10)
d <- rep(10,20)
c <- c(a,d)
但如果希望cbind()工作,则必须确保“d”足够小,可以循环使用:

a <- rep(6,10)
b <- rep(8,10)
c <- cbind(a,b)
d <- rep(10,5)
x <- cbind(c,d)

您正在寻找一个
?列表
您希望它们如何“组合”?作为一个表格,在
c
列的第11-20行中有
NA
s?A
列表
l也可以使用
df在“空”行中使用
NA
s创建
dataframe
a <- rep(6,10)
d <- rep(10,20)
c <- c(a,d)
> c
 [1]  6  6  6  6  6  6  6  6  6  6 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
a <- rep(6,10)
b <- rep(8,10)
c <- cbind(a,b)
d <- rep(10,5)
x <- cbind(c,d)
> x
      a b  d
 [1,] 6 8 10
 [2,] 6 8 10
 [3,] 6 8 10
 [4,] 6 8 10
 [5,] 6 8 10
 [6,] 6 8 10
 [7,] 6 8 10
 [8,] 6 8 10
 [9,] 6 8 10
[10,] 6 8 10