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

Jeff Newmiller jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Mon Jul 1 20:50:09 CEST 2024


I think you should reconsider your goal. Matrices must have all elements of the same type, and in this case you seem to be trying to mix a number of something (integer) with mean values (double). This would normally be stored together in a data frame or separately in a vector for counts and a matrix for means.

If you are just thinking about data presentation, a data frame would be a better choice than a single matrix.

On July 1, 2024 8:54:21 AM PDT, "Sorkin, John" <jsorkin using som.umaryland.edu> wrote:
>#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
>
>
>
>______________________________________________
>R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

-- 
Sent from my phone. Please excuse my brevity.



More information about the R-help mailing list