[R] Create matrix with variable number of columns AND CREATE NAMES FOR THE COLUMNS
Heinz Tuechler
tuech|er @end|ng |rom gmx@@t
Mon Jul 1 20:55:07 CEST 2024
Sorkin, John wrote/hat geschrieben on/am 01.07.2024 17:54:
> #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
>
maybe:
NSims <- 4
Grps <- 5
DiffMeans <-
matrix(nrow=NSims,ncol=1+Grps,
dimnames=list(NULL, c('Nsimn', paste('Item', 1:Grps, sep=''))))
DiffMeans
best,
Heinz
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list