我知道这是一个相当简单的问题,但我一直找不到答案,这让我发疯了。
我有一个矩阵,有两列:
[,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值的连续逻辑函数的结果。如果你想帮我修复我对代码的嘲弄,我将不胜感激。这是我需要帮助的代码示例:
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(到向量('2'((-1(的length
的行索引序列,创建序列(:
(,并将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
输出:
[,1] [,2]
[1,] 0 1
[2,] 0 2
[3,] 0 3
[4,] 0 4
[5,] 0 5
[6,] 0 6