简体   繁体   中英

R: repeat a for loop which uses two variables in a dataset for the rest of the pairs of variables in the dataset

I have a dataset containing pairs of a lot of variables/columns, for example a1 and a2 , b1 and b2 , c1 and c3 , etc.

I've written a for loop in R which creates a new variable a_new using both the columns a1 and a2 (specifically, I am using an if else function in between the for loop).

I want to do the same for the rest of variables/columns, creating columns b_new , c_new , etc. from b1 and b2 , c1 and c2 , etc. without writing 100 for loops, so I maybe need to use one of the apply functions (or another for loop which loops around the for loop I already have?).

Can anyone help me out?

As you don't provide any code example I will asume that you're just adding up one column to another.

In this case you can:

#Dummy data    
DF=data.frame(replicate(10,sample(0:1,1000,rep=TRUE)))

#For loop
for(i in (which(seq(1:ncol(DF)) %% 2 == 1))){
DF[paste("new_",i,sep="")]=DF[i]+DF[i+1]}

This will create a new column within "DF" with the result of the first column in "DF" + the second column in "DF". The operation can change in any way you want.

As it use ncol(DF) into the loop it will adjust to the size of the table you're working on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM