Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic column name in for loop with cbind

Tags:

r

I'm trying a loop like this, where I want to assign the name of the matrix column dynamically:

for(i in 1:nclass){   P <- eXb / SeXb[mydata$chid]   mydata <- cbind(mydata, paste("l_", i, sep="")=P) } 

Any idea (apart from changing colnames ex-post)?

Thanks

like image 254
danfreak Avatar asked Mar 30 '12 22:03

danfreak


2 Answers

What about this? You would set column names after you've got your fully worked out matrix finished.

> a <- matrix(1:9, 3) > a      [,1] [,2] [,3] [1,]    1    4    7 [2,]    2    5    8 [3,]    3    6    9 > colnames(a) <- paste("col", 1:3, sep = "") > a      col1 col2 col3 [1,]    1    4    7 [2,]    2    5    8 [3,]    3    6    9 
like image 164
Roman Luštrik Avatar answered Oct 03 '22 05:10

Roman Luštrik


If you have the problem that you don't know the number of the added column, you can add and name them by:

df <- data.frame(matrix(1:9, 3, 3)) df #>  X1 X2 X3 #>1  1  4  7 #>2  2  5  8 #>3  3  6  9  for(i in 1:5){   df[, ncol(df) + 1] <- rnorm(nrow(df))   names(df)[ncol(df)] <- paste0("mean_", i) }  df #>  X1 X2 X3     mean_1     mean_2    mean_3     mean_4     mean_5 #>1  1  4  7 -1.9983501 -1.6810377 1.2893602  0.5342042 -0.8354363 #>2  2  5  8  0.5966507 -0.5628999 1.2953387 -0.6661931 -0.4685747 #>3  3  6  9 -0.4268952 -2.0069306 0.6390317 -0.3505088  0.1230753 
like image 34
loki Avatar answered Oct 03 '22 05:10

loki