-1

So I have a dataset with variables

A_1    B_1     A_2    B_2    A_3    B_3......A_721    B_721

I made variable C_1 using an ifelse statement with A_1 and B_1. Something like:

Data$C_1 <- ifelse(A_1 - B_1 <= 365 & A_1 - B_1 >= 0, 1, 0)

I want to make this rerun 721 times, to create C_1 to C_721 using the respective A and B variables.

All the examples of loops I find online run down a single column, and not across enumerated columns like I want to do here.

I apologize for the simplistic example, but I'm not sure if I can do this using a loop, or apply, or where to start.

Shree
  • 10,835
  • 1
  • 14
  • 36
fwarner
  • 55
  • 6
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. (A useful example doesn't have to have all 721 columns.) – MrFlick Dec 03 '18 at 19:48

1 Answers1

-1

This should work but cannot check without reproducible example

        for(i in 1:721)
        {
             assign(paste("C_",i,sep=""),
ifelse(get(paste('A_',i,sep="")) - get(paste('B_',i,sep="")) <= 365 & get(paste('A_',i,sep="")) - get(paste('B_',i,sep="")) >= 0, 1, 0)
    }

After this you can just use cbind to attach the C columns to your data

  • Thank you! it says "B_" is not found... is there a way to specify which dataset this variable exists in? – fwarner Dec 03 '18 at 20:16
  • 1
    I advise against writing such code in the strongest possible terms. Use lists and data.frames instead. *This is bad code*. – Konrad Rudolph Dec 03 '18 at 20:31
  • Try writing get('B_1') and see if it returns value. – Anindya Sankar Dey Dec 03 '18 at 21:14
  • I understand its bad code but without example and more info, it not possible to get a solution which is elegant. Instead of just posting that it's a bad solution, it'd be better if negative reviewers give a better solution. – Anindya Sankar Dey Dec 03 '18 at 21:16