【问题标题】:How to add multiple columns to a matrix when number of columns for that matrix is known in R?当 R 中已知矩阵的列数时,如何将多列添加到矩阵中?
【发布时间】:2019-05-08 23:25:08
【问题描述】:

我正在尝试创建一个函数来遍历加载为矩阵的 .csv 文件(我在它们上使用该函数时一个一个),它将添加第 19、20、21、22、23 和 24 列。这些矩阵都有 18 列,所以我从第 19 列开始,所以我不会删除任何以前的数据。它应该首先提示第 19 列和第 22 列的数据(作为数字),然后计算其余列的数据。我不断收到“新列会在现有列之后留下漏洞”消息。

我尝试从尝试分配 matrix[,19] 切换到执行 cbind(matrix, c("name of column 19", "name of column 20", etc.) ,但都不起作用。

func<- function(matrix){
  cbind(matrix, c("name19","name20", "name21", "name22", "name23", "name24"))
  matrix[,19] <- as.numeric(readline(prompt = "enter number ")) 
  matrix[,22] <- as.numeric(readline(prompt = "enter number "))
  matrix[x,20] <- 1.25*(matrix$colname10[x]/4) 
  matrix[x,21] <- matrix[x,20]/(15*matrix[x,19])
  matrix[x,23] <- 1.25*(matrix$colname13[x]/4) 
  matrix[x,24] <- matrix[x,23]/(15*matrix[x,22]) 
    }
func(matrixwith18cols)

这给出了我的错误

我没有添加新列并对我要求的观察结果进行数学运算并添加新观察结果,而是得到 ​​p>

Error in `[<-.data.frame`(`*tmp*`, , 22, value = 1) : 
  new columns would leave holes after existing columns

在控制台中(在我输入 1 作为两个提示之后)

【问题讨论】:

  • 我们迫切需要minimal reproducible example。该错误消息强烈表明您使用的不是矩阵而是数据框。
  • 哦,谢谢!我认为我的示例是完整的,因为我认为我正在使用矩阵,但你是对的,它是一个数据框。我相信这是我遇到问题的主要原因

标签: r


【解决方案1】:

我会创建一个要添加的矩阵(在您的 cbind 中,您将矩阵绑定到一个向量,我不知道 R 会对此有何反应)。

此外,您的 cbind 函数的输出不会保存在新矩阵中。 所以我会怎么做:

mat.to.add = matrix(NA, nrow = nrow(matrix), ncol = 6)
marix = cbind(matrix, mat.to.add)

然后进行数学运算

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 2014-07-06
    • 2015-06-21
    • 1970-01-01
    相关资源
    最近更新 更多