繁体   English   中英

将一行数字/一个向量附加到 R 中的现有矩阵列

[英]Attaching a row of numbers/ a vector to an existing Column of a Matrix in R

我知道这是一个相当简单的问题,但我无法找到答案,这让我发疯。

我有一个包含两列的矩阵:

   [,1][,2]
[1,]  0   1
      0   2
      0   3

我想将一系列数字添加到第二列(例如 4,5,6),使其变为:

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

如果我尝试:

 Matrix[,2]<-rbind(c(4,5,6))
 Matrix[,2]<-c(4,5,6)     

和类似的东西我得到一个错误,或者它覆盖了所有以前的数字。 我问是因为我想创建一个包含两列的矩阵,其中需要保存具有不同 r 值的连续逻辑 function 的结果。 如果您想帮助我解决我对代码的嘲弄,我将不胜感激。 这是我需要帮助的代码示例:

rdvec<-c(seq(from=1,to=3,by=0.02))
vec<-numeric()
for (i in 1:length(rdvec)){
    rd<-rdvec[i]
    vec<-logfun(N0, rd, K, schritte) # the logistic function
    vec<-vec[-c(1:100)] # i only need the second half of the results
    # and this is where i need help creating/updating a matrix
    Matrix[,2]<-rbind(Matrix,vec) # Ive tried this and variations of it but it obviously 
                                    doesnt work
}

您能给我的任何帮助都将不胜感激。

如果打算扩展数据的行,一个选项是创建从最后一行 (+1) 到向量length ('n2') (-1) 的行索引序列,创建序列( : ),然后将data.frame中的这些新行分配给由cbind ing 0 和vec创建的两列

n1 <- (nrow(Matrix) + 1)
n2 <- n1 + length(vec)-1
d1 <- as.data.frame(Matrix)
d1[n1:n2,] <- cbind(0, vec)
d1

或者以另一种方式来绑定和更新相同的rbind

Matrix <- rbind(Matrix, cbind(0, vec))

数据

Matrix <- cbind(0, 1:3)
vec <- 4:6

如果您仍然坚持使用for循环,您也可以使用以下解决方案。 但是,亲爱的@akrun 提出的其他解决方案效率更高:

# Here is your original matrix
mx <- matrix(c(0, 0, 0, 1, 2, 3), ncol = 2)

# I defined a custom function that takes a matrix and the vector to be added
# to the second column of the matrix

fn <- function(mx, vec) {
  out <- matrix(rep(NA, 2 * length(vec)), ncol = 2)
  
  for(i in 1:nrow(out)) {
    out[i, ] <- mx[nrow(mx), ] + c(0, i)
  }
  rbind(mx, out)
}

fn(mx, c(4, 5, 6))

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

我们可以这样做:

x <- matrix(1:6, 6, 2)
y <- matrix(rep( 0, len=6), nrow = 6)
x[,1] <- y[,1]
x

Output:

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

暂无
暂无

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

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