I would like to create a loop that will add now variables to the data frame.Those variables should be the simple quadratic form of the exsiting varibles.
In the example below I would like to have 3 new vars that are : dat$birds_2 <- dat$birds^2
; dat$wolfs_2 <- dat$wolfs^2
; dat$snakes_2 <- dat$snakes^2
. I would like to do this for multiple variables at once.
dat <- read.table(text = " birds wolfs snakes
3 9 7
3 8 4
1 2 8
1 2 3
1 8 3
6 1 2
6 7 1
6 1 5
5 9 7
3 8 7
4 2 7
1 2 3
7 6 3
6 1 1
6 3 9
6 1 1 ",header = TRUE)
The needed output (dat_new
) is (I show only the first 2 rows) :
dat_new birds wolfs snakes birds_2 wolfs_2 snakes_2
3 9 7 9 81 49
3 8 4 9 64 16
An option using
data.table
Or you can use
set
(which would be more efficient) as there are multiple columnsBenchmarks
In a one liner with
setNames
:As an alternative, you can also do this quite easily with the
dplyr
package:this gives:
If you want to get quadratic values for some variables (eg variables 1 to 10 of
dat
), you can do:If you want to do that for all the variables of your original data.frame, you can do:
with your
dat
, you'll get:You can do the following (not using a loop):