如何向数据框添加新的计算变量 [英] How to add new calculated variables to a data frame

查看:157
本文介绍了如何向数据框添加新的计算变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个循环,现在可以将变量添加到数据框架中。这些变量应该是exsiting可变的简单二次形式。
在下面的示例中,我想要有3个新的var:$ code> dat $ birds_2 < - code>; dat $ wolfs_2< - dat $ wolfs ^ 2 ; dat $ snakes_2< - dat $ snakes ^ 2 。我想一次为多个变量执行此操作。

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)

需要的输出( dat_new )是(我只显示前2行s):

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


推荐答案

c $ c> setNames :

In a one liner with setNames:

setNames(as.data.frame(cbind(dat, dat^2)), c(names(dat), paste0(names(dat),'_2')))

#   birds wolfs snakes birds_2 wolfs_2 snakes_2
#1      3     9      7       9      81       49
#2      3     8      4       9      64       16

这篇关于如何向数据框添加新的计算变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆