I came up with this solution, > cbind(dat, dat[, 1:3]^2) X1 X2 X3 X4 X5 X1 X2 X3 1 0.72776481 -1.1332612 -1.9857503 0.46189400 -0.09016379 0.529641625 1.28428102 3.9432044 2 0.05126592 0.2858707 0.9075806 1.27582713 -0.49438507 0.002628194 0.08172203 0.8237026 3 -0.40430146 0.5457195 -1.1924042 0.15025594 1.99710475 0.163459669 0.29780978 1.4218277 4 1.40746971 -1.2279416 0.3296075 0.84411774 -0.52371619 1.980970990 1.50784058 0.1086411 5 -0.53841150 0.4750082 -0.4705148 0.05591914 -0.31503500 0.289886944 0.22563275 0.2213842 6 0.90691210 0.7247171 0.8244184 0.73328097 -1.05284737 0.822489552 0.52521494 0.6796657
But, you would NOT ONLY get undesired variable names, BUT ALSO duplicated names. I suppose I can use paste() to solve that? Any better ideas? On Fri, Apr 28, 2017 at 8:57 PM, C W <tmrs...@gmail.com> wrote: > Dear R list, > > I am am a little unsure what is the best way to approach this. I suppose I > have > > > dat <- matrix(rnorm(30), ncol = 5) > > dat <- data.frame(dat) > > dat > X1 X2 X3 X4 X5 > 1 -1.13999917 -0.87868106 -0.33000492 1.5241765 -0.92483388 > 2 -0.56168006 -0.08837883 1.96237792 -0.5335615 0.02880586 > 3 0.82800071 -1.89965562 -0.05438815 -0.9162857 -0.57470053 > 4 -0.03218412 -0.23119263 -1.10671765 -0.2885518 -0.30953951 > 5 1.70525779 -0.93854817 -1.05932636 -0.2983139 -0.21980145 > 6 1.19047531 0.38301678 -0.20830015 -0.6668266 0.82578534 > > Suppose I want to add columns X6, X7, X8, where > X6 = X1^2 > X7 = X2^2 > X8 = X3^2 > > I am thinking of using apply(), but df asks for column names, what's a > quick way to generate names on the fly? > > Thank you very much! > > [[alternative HTML version deleted]] ______________________________________________ R-help@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.