Ben
Ben

Reputation: 103

How to add multiple columns to a matrix when number of columns for that matrix is known in R?

I'm trying to create a function to go over .csv files loaded as matrices (one by one as I use the function on them) that will add a 19th, 20th, 21st, 22nd, 23rd, and 24th column. These matrices will all have 18 columns, so I'm starting at column 19 so I don't erase any of the previous data. It should first prompt the data for the 19th and 22nd columns (as a numeric) and then compute the data for the rest of the columns. I keep getting the "new columns would leave holes after the existing columns" message.

I've tried switching from just trying to assign matrix[,19] to doing cbind(matrix, c("name of column 19", "name of column 20", etc.) and neither works.

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)

This gives my error

Instead of adding new columns and doing the math on the observations I ask it to and adding new observations, I get

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

in the console (After I enter in 1 as both prompts)

Upvotes: 0

Views: 1535

Answers (1)

glagla
glagla

Reputation: 611

I would create a matrix to add (here in your cbind, you are binding your matrix to a vector, I don't know how R would react to that).

Also, the output of your cbind function is not saved in the new matrix. So what I would do:

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

and then do your mathematical operations

Upvotes: 1

Related Questions