我想在数据框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代码?
答案 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