Looping over columns in R to create new columns

I am trying to loop over the column names of an existing data frame, and then create new columns based on one of the old columns. Here are my details:

 sample<-list(c(10,12,17,7,9,10),c(NA,NA,NA,10,12,13),c(1,1,1,0,0,0))
    sample<-as.data.frame(sample)
    colnames(sample)<-c("x1","x2","D")

>sample
x1  x2  D
10  NA  1
12  NA  1
17  NA  1
7   10  0
9   20  0
10  13  0

Now I'm trying to use for looptwo variables, x1.imp and x2.imp, to have values ​​associated with D = 0 when D = 1 and values ​​associated with D = 1 when D = 0 (I really don't need here for loopbut for my original dataset with large columns (variables) I really need a loop) based on the following condition:

for (i in names(sample[,1:2])){
sample$i.imp<-with (sample, ifelse (D==1, i[D==0],i[D==1]))
i=i+1
return(sample)
}


Error in i + 1 : non-numeric argument to binary operator

However, the following works, but it does not give the names of the new cols like imp.x2 and imp.x3

for(i in sample[,1:2]){
impt.i<-with(sample,ifelse(D==1,i[D==0],i[D==1]))
i=i+1
print(as.data.frame(impt.i))
 }

impt.i
1      7
2      9
3     10
4     10
5     12
6     17
  impt.i
1     10
2     12
3     13
4     NA
5     NA
6     NA

Note that I already know the solution without a loop [here] . I want with a loop.

Expected Result:

x1  x2  D   x1.impt x2.imp 
10  NA  1   7       10      
12  NA  1   9       20
17  NA  1   10      13
7   10  0   10      NA
9   20  0   12      NA
10  13  0   17      NA

.

+1
2

, ... :

for (i in colnames(sample)[1:2]){
  sample[[paste0(i, '.impt')]] <- with(sample, ifelse(D==1, get(i)[D==0],get(i)[D==1]))
}

:

  • names(sample[,1:2]) colnames(sample)[1:2]
  • $ . , , , [ [[, sample$i.imp sample[[paste0(i, '.impt')]]
  • with, i[D==0] x1[D==0], i "x1", get.
  • data.frame sample,
+3

,

test <- sample[,"D"] == 1
for (.name in names(sample)[1:2]){
  newvar <- paste(.name, "impt", sep=".")
  sample[[newvar]] <- ifelse(test, sample[!test, .name], 
                                   sample[test, .name]) 
}

sample
+1

All Articles