Drop columns of dataframe based on a vector and based on repeated sequence

I am trying to drop columns from a huge dataframe depending on a vector.

Example dataframe:

df1 <- data.frame(replicate(60, sample(0:10, 1, rep=TRUE)))

  X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15 X16 X17 X18 X19 X20 X21 X22 X23 X24 X25
1  4  6  0  7  3  5  6  9  2   6   5   2   4   0  10   5   7   6   2   9   0   1   4  10   1
  X26 X27 X28 X29 X30 X31 X32 X33 X34 X35 X36 X37 X38 X39 X40 X41 X42 X43 X44 X45 X46 X47 X48
1   5   8   8   7   7   8   7   3   4   5   2   4   4   0   6   4   5   0   8   5   6  10  10
  X49 X50 X51 X52 X53 X54 X55 X56 X57 X58 X59 X60
1   6   9  10   5   5   1   2  10   3   0   0  10


Important note on the dataframe:
Each 1-6 column belongs to one stack. This means:
X1 to X6 is stack 1
X7 to X12 is stack 2
X13 to X18 is stack 3
X19 to X24 is stack 4
...until...
X55 to X60 is stack 10.

Example vector:

v1 <- c(1, 3, 7)

Important note on the vector:
The values in the vector refer to the stack number. In my example I would like to drop stack 1, 3 and 7. Dropping stack 1 means dropping columns x1-X6, dropping stack 3 means dropping columns x13-X18 and dropping stack 7 means dropping columns X37:X42.

The output I am trying to achieve should look like this:

  X7 X8 X9 X10 X11 X12 X19 X20 X21 X22 X23 X24 X25 X26 X27 X28 X29 X30 X31 X32 X33 X34 X35 X36 X43 X44 X45 X46 X47 X48 X49
1  6  9  2   6   5   2   2   9   0   1   4  10   1   5   8   8   7   7   8   7   3   4   5   2   0   8   5   6  10  10   6
  X50 X51 X52 X53 X54 X55 X56 X57 X58 X59 X60
1   9  10   5   5   1   2  10   3   0   0  10

My solutions are:

df2 <- df1[,-c(1,2,3,4,5,6,13,14,15,16,17,18,37,38,39,40,41,42)]

df2 <- df1[,-c(1:6, 13:18, 37:42)]

But my dataframe is huge and I have several other vectors. Therefore I don't want to count every time and write the correct numbers manually. I would like to use the information of the vector directly.

Is there any way I can use the the vector v1 <- c(1,3,7) to achieve the desired output?

I tried different things with rep() and seq(), but failed.

Try following funtion to find drop index. Please let me know if it works.

mydrop<-function(v){
  vx<-c()
  for (j in v) {
    vx<-c(vx,(6*j-5):(6*j))
  }
  return(vx)
}
v1<-c(1,3,7)
df2 <- df1[,-mydrop(v1)]
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.