[R] Create matrix with variable number of columns AND CREATE NAMES FOR THE COLUMNS
Rui Barradas
ru|pb@rr@d@@ @end|ng |rom @@po@pt
Mon Jul 1 20:05:32 CEST 2024
Às 16:54 de 01/07/2024, Sorkin, John escreveu:
> #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.
Hello,
Sorry for my first answer, I thought you only wanted to name the matrix
columns. After reading the OP again, this time actually reading it, I
realized you also want to create the matrix. This is even in the
question title line :(.
create_matrix <- function(nsims, ngrps, First = "NSims", Prefix = "Value") {
# could also be paste0(Prefix, seq_len(ngrps))
grp_names <- sprintf("%s%d", Prefix, seq_len(ngrps))
nms <- c(First, grp_names)
matrix(nrow = nsims, ncol = 1L + ngrps, dimnames = list(NULL, nms))
}
NSims <- 4
Grps <- 5
create_matrix(NSims, Grps)
#> NSims Value1 Value2 Value3 Value4 Value5
#> [1,] NA NA NA NA NA NA
#> [2,] NA NA NA NA NA NA
#> [3,] NA NA NA NA NA NA
#> [4,] NA NA NA NA NA NA
Hope this helps,
Rui Barradas
--
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença de vírus.
www.avg.com
More information about the R-help
mailing list