# [R] [FORGED] Re: How create columns for squared values from previous columns?

Rolf Turner r.turner at auckland.ac.nz
Sat Apr 29 04:48:42 CEST 2017

```On 29/04/17 13:21, C W wrote:
> 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?

Well, if the names bizzo is your only worry, you could hit the result
with data.frame() *after* cbinding on the squared terms:

dat <- matrix(rnorm(30),ncol=5)
dat <- cbind(dat,dat[,1:3]^2)
dat <- data.frame(dat)
names(dat)

And as you indicate, the names of a data frame are easily adjusted.

I wouldn't lose sleep over it.

cheers,

Rolf Turner

P.S. You could also do

names(dat) <- make.unique(names(dat))

to your original idea, to get rid of the lack of uniqueness.  The result
is probably "undesirable" but.

R. T.

--
Technical Editor ANZJS
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276

```