如何创建自动索引变量

时间:2014-05-26 14:36:28

标签: r variables

我需要知道如何在data.frame中的R 索引变量中创建。

示例:我在data.frame(dat)中有P1,P2,P3,B1,B2,B3数值变量,我必须创建新变量:I1 = P1 / B1,I2 = P2使用for循环,data.frame dat 中的/ B2和I3 = P3 / B3。

也许我不清楚,抱歉。我必须创建变量(100)Ik,我不想写:

dat$I1<-dat$P1/dat$B1  
dat$I2<-dat$P2/dat$B2
dat$I3<-dat$P3/dat$B3    
...
dat$I99<-dat$P99/dat$B99
dat$I100<-dat$P100/dat$B100

肯定可以这样做:

for(k in 1:100) {
    ???
}

非常感谢!

3 个答案:

答案 0 :(得分:2)

您只需使用以下代码创建新变量:

# creating a example dataframe
dat <- data.frame(P1=rnorm(100,40,4), P2=rnorm(100,20,2), P3=rnorm(100,10,1),
                  B1=rnorm(100,10,2), B2=rnorm(100,5,1), B3=rnorm(100,2.5,1))

# creating the new variables
dat$I1 <- dat$P1/dat$B1
dat$I2 <- dat$P2/dat$B2
dat$I3 <- dat$P3/dat$B3

编辑:延伸@ agstudy的答案:

# creating a new dataframe based on @agstudy's
nn <- colnames(dat)
i123 <- mapply(function(x,y)dat[,x]/dat[,y],grep('P',nn),grep('B',nn))
i123 <- as.data.frame(i123)
colnames(i123) <- c("I1","I2","I3")

# adding the dataframe with the new variables to the existing dataframe
dat <- cbind(dat,i123)

答案 1 :(得分:2)

可以使用data.table

轻松完成
library(data.table)
setDT(dat)[, c("I1", "I2", "I3") := list(P1/B1, P2/B2, P3/B3)]

答案 2 :(得分:1)

在R中,我们尽量避免使用for循环,因为它们有副作用。您应该使用R方式执行以下操作:

  • 使用矢量化操作
  • 使用众多xxapply家庭功能之一

例如,在这里使用mapply,我得到@Jaap答案的通用版本:

nn <- colnames(dat)
mapply(function(x,y)dat[,x]/dat[,y],grep('P',nn),grep('B',nn))

PS:在某些情况下我们别无选择,我们使用for loop,特别是迭代之间存在一些递归关系。