R:从字符向量创建矩阵,并将NA保留在矩阵中

时间:2018-08-04 09:47:30

标签: r matrix vector na

我想从类似于以下的字符向量创建矩阵:

comments <- c("abc", "lol")
comm_matrix <- matrix(data=comments, ncol=3, nrow=1)

我想获取矩阵,但是如果向量中的ncol> nchar则为NA:

[,1] [,2] [,3]
abc  lol  NA 

代替默认值:

[,1] [,2] [,3]
abc  lol  abc

1 个答案:

答案 0 :(得分:1)

感谢同伴, 解决方案是:

comments <- c("abc", "lol")
length(comments) <-prod(dim(matrix(comments, ncol=3)))
comm_matrix <- matrix(data=comments, ncol=3, nrow=1, byrow=TRUE)
comm_matrix

#    [,1]  [,2]  [,3]
#[1,] "abc" "lol" NA