[R] Create matrix with variable number of columns AND CREATE NAMES FOR THE COLUMNS

Sorkin, John j@ork|n @end|ng |rom @om@um@ry|@nd@edu
Mon Jul 1 17:54:21 CEST 2024


#I am trying to write code that will create a matrix with a variable number of columns where the #number of columns is 1+Grps
#I can do this:
NSims <- 4
Grps <- 5
DiffMeans <- matrix(nrow=NSims,ncol=1+Grps)
DiffMeans

#I have a problem when I try to name the columns of the matrix. I want the first column to be NSims, #and the other columns to be something like Value1, Value2, . . . Valuen where N=Grps

# I wrote a function to build a list of length Grps
createValuelist <- function(num_elements) {
  for (i in 1:num_elements) {
    cat("Item", i, "\n", sep = "")
  }
}
createValuelist(Grps)

# When I try to assign column names I receive an error:
#Error in dimnames(DiffMeans) <- list(NULL, c("NSim", createValuelist(Grps))) : 
# length of 'dimnames' [2] not equal to array extent
dimnames(DiffMeans) <- list(NULL,c("NSim",createValuelist(Grps)))
DiffMeans

# Thank you for your help!


John David Sorkin M.D., Ph.D.
Professor of Medicine, University of Maryland School of Medicine;
Associate Director for Biostatistics and Informatics, Baltimore VA Medical Center Geriatrics Research, Education, and Clinical Center; 
PI Biostatistics and Informatics Core, University of Maryland School of Medicine Claude D. Pepper Older Americans Independence Center;
Senior Statistician University of Maryland Center for Vascular Research;

Division of Gerontology and Paliative Care,
10 North Greene Street
GRECC (BT/18/GR)
Baltimore, MD 21201-1524
Cell phone 443-418-5382





More information about the R-help mailing list