Gistlib Logo

gistlib

when a column does not exists as a row in a matrix, add a new one as a row of zeros in r

main.r
# Create a matrix
mat <- matrix(1:12, nrow = 3, ncol = 4)

# Define the column to be added
col_to_add <- "5"

# Check if the column exists, if not add a new column of zeros
if(col_to_add %in% colnames(mat)){
  cat("Column already exists")
} else {
  mat <- cbind(mat, numeric(nrow(mat)))
  colnames(mat)[ncol(mat)] <- col_to_add
}
331 chars
14 lines

similar r code snippets

matrix, how tu use in r
r matrix in r
create a loop that brings in matricies from csv files and adds them all together in r
create a community matrix and use its laplacian matrix to get eigenvectors sorted by their corresponding eigenvalue in non-decreasing order. then use k means algorithm and plot a cluster graph in r
multiply matrices in r
normalize a laplacian matrix in r
create a loop to bring in a matrix csv file convert it to a numeric matrix and then add the matrices together in r
convert character matrix to numeric in r
correlation matrix with certain variables in r
load a spreadsheet into r. combined the first four rows and six columns into a matrix and if there are duplicate values in the matrix, randomise all rows in r

related categories

r
matrix

gistlibby LogSnag