简体   繁体   中英

Naming matrix columns within a nested loop in R

I would like to produce a matrix using an R loop (for other reasons I don't want to use vectors in this case, which would be amenable to outer() ), such that the columns came labeled with the pair i , j corresponding to the iterations of the loop. For instance, (1,3) .

I'm used to starting a vector outside the loop with NA or 0 assigned to it. I know that determining the dimensions ahead of time is more efficient. But I don't want to have to determine the dimensions in more complex problems of this type, and within the loop I don't know how to fill in the vector. Usually I would code it as vector[i] <- new value to add , but here I am juggling two indexes, i and j , and if I index it like vector[i,j] <- new value to add I believe R gets confused thinking of a matrix.

Here is the non-working code:

x1=c(1,4,2,5,6)
x2=c(5,3,7,7,8)
data=data.frame(x1,x2)
data=as.matrix(data)
n = 6 # polynomial degree

for(i in 1:n){
  for(j in 0:n){
    data = cbind(data,data[,1]^(i-j) * data[,2]^j)
    colnames(data) = paste("(",i,",",j,")")
  }
}

data

The simplest answer would be to change

colnames(data) = paste("(",i,",",j,")")

to

colnames(data)[ncol(data)] = paste("(",i,",",j,")")

cause you want to change only last column (the one recently added).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM