将数字行/a向量附加到R中矩阵的现有列
我知道这是一个相当简单的问题,但我一直没有找到答案,这让我发疯 我有一个包含两列的矩阵:将数字行/a向量附加到R中矩阵的现有列,r,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))
[,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)
矩阵[,2]如果目的是扩展数据行,一个选项是创建从最后一行(+1)到向量('n2')(-1)长度的行索引序列,创建序列(:
),并将data.frame
中的新行分配给cbind
ing 0和vec
tor创建的两列
n1 <- (nrow(Matrix) + 1)
n2 <- n1 + length(vec)-1
d1 <- as.data.frame(Matrix)
d1[n1:n2,] <- cbind(0, vec)
d1
数据
Matrix如果仍然坚持使用for
循环,也可以使用以下解决方案。然而,dear@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
#这是您的原始矩阵
mx我们可以做:
x <- matrix(1:6, 6, 2)
y <- matrix(rep( 0, len=6), nrow = 6)
x[,1] <- y[,1]
x
Matrix <- cbind(0, 1:3)
vec <- 4:6
# 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