Search code examples
rif-statementdataframeconditional-statementscbind

Shifting Column Selection in Dataframe in R


I have a data frame with 30 columns. My goal is to select 5 columns at a time. Based on a condition, I want to shift my selection in the data frame 5 columns.

For example:

Original dataframe column selection:

Col6 Col7 Col8 Col9 Col10

If condition is true, select:

Col1 Col2 Col3 Col4 Col5

If condition is false, select:

Col11 Col12 Col13 Col14 Col15.

I don't want to call out those specific columns though, I want to write a general formula that would call out a shift of 5 columns to the right or left based on whether the condition was true or false.

Any help would be great. Thanks!


Solution

  • From what you asked I developed the following code. Please clarify the question if this is not what you are looking for. Assuming that your data frame is df:

    n <- 1
    
    df[,n:n+4]
    
    if (condition){
      n <- n + 5
    } else if (condition && n != 1) {
      n <- n - 5
    }