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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With