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
See Question&Answers more detail:os