使用for循环将伪变量添加到data.frame

时间:2014-05-29 20:12:39

标签: r for-loop dataframe

我想在数据框t1, t2, ..., t100中添加100个假人DF

DF$'t1' <- ifelse(DF$x==1, 1, 0)
DF$'t2' <- ifelse(DF$x==2, 1, 0)
...
DF$'t100' <- ifelse(DF$x==100, 1, 0)

使用for-loop,我尝试像这样编码:

for (i in 1:100) DF$paste("t","i",sep="") <- ifelse(DF$x == i, 1, 0)

你能否纠正R代码?

2 个答案:

答案 0 :(得分:3)

for (i in 1:100){

    DF[[paste("t",i,sep="")]] <- ifelse(DF$x == i, 1, 0)

}

答案 1 :(得分:1)

请考虑以下示例:

#dummy data
x<- matrix(c(1:10,sample(1:15,10)),ncol=2)

#make empty matrix
y <- matrix(rep(0,length(x)*15),ncol=15)

#mark relevant cell
y[x] <- as.logical(x[,1])*1

#pretty output
y <- as.data.frame(y)
colnames(y) <- paste0("t",1:15)
df <- cbind(x=x[,2],y)

df