Coho13
Coho13

Reputation: 5

Create list in R for column names

I am trying to create a list that will vary and be interchangeable for different uses. I want it to be in the pattern of:

P1A1 P1A2 P1A3 P1A4 P1A5 P1A6 
P2A1 P2A2 P2A3 P2A4 P2A5 P2A6
P3A1 P3A2 P3A3 P3A4 P3A5 P3A6

Where P goes from 1 to num.Patches and A goes from 1 to num.allele. So for the example above, num.Patches = 3 and num.alleles =6

I am trying to use a for loop:

pdum <- matrix(data=NA,nrow=1,ncol=num.Patches)
Adum <- matrix(data=NA,nrow=1,ncol=num.allele*num.Patches+1)  
key2 <- matrix(data=NA,nrow=1,ncol=num.allele*num.Patches+1)

for (i in 1:num.Patches) pdum[1,i] <- matrix(paste("P",i,sep=""))
pdum2 <- as.character(pdum)

for (k in 1:num.Patches){
  for (i in pdum2) {
    for (j in 1:num.allele){
     Adum[1,k+num.allele*(1-j)] <- matrix(paste(i,"A",j,sep=""))
    }
  }
}

The line that I am having trouble with is:

Adum[1,k+num.allele*(1-j)] <- matrix(paste(i,"A",j,sep=""))

I don't know how to reference each entry of the Adum matrix and fill it in with a particular value. The end goal of this is to create a list to use as column names of a larger matrix so that it can be referenced easily.

Thank you very much.

Upvotes: 0

Views: 615

Answers (2)

josliber
josliber

Reputation: 44299

To get all combinations of 1:num.Patches and 1:num.alleles and then combine, you could try:

combinations <- expand.grid(1:num.Patches, 1:num.alleles)
names <- paste0("P", combinations[,1], "A", combinations[,2])

This would give you the patterns you wanted (as a vector). You could later set them as the column names of some matrix you created.

Upvotes: 2

agstudy
agstudy

Reputation: 121568

You are looking for outer:

num.Patches <- 3
num.alleles <- 6

mm <- outer(seq(num.Patches), seq(num.alleles),
            function(x,y)paste0('P',x,'A',y))

     [,1]   [,2]   [,3]   [,4]   [,5]   [,6]  
[1,] "P1A1" "P1A2" "P1A3" "P1A4" "P1A5" "P1A6"
[2,] "P2A1" "P2A2" "P2A3" "P2A4" "P2A5" "P2A6"
[3,] "P3A1" "P3A2" "P3A3" "P3A4" "P3A5" "P3A6"

If you want to get a vector of names:

as.vector(mm)

Upvotes: 2

Related Questions