So I have a dataframe with an unspecified number of columns (all I know is there would be at least 4 columns).
What I want to do is, for every 4 columns, I want to delete columns 3 and 4.
So let's say my dataframe contains 12 columns. In that case, I want to delete columns 3, 4, 7, 8, 11, 12.
I know that I can delete a column every nth column like this:
df <- df[,seq(2,ncol(df),4)]
But how can I delete every 3rd and 4th column in the same way using R?
Thank you.
As these are index, use - to remove those columns
i1 <- rep(seq(3, ncol(df), 4) , each = 2) + 0:1
df[,-i1]
Or another option is to use a logical index to recycle
df[!c(FALSE, FALSE, TRUE, TRUE)]
set.seed(24)
df <- as.data.frame(matrix(rnorm(12 * 4), 4, 12))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With