Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove multiple columns every nth column in R?

Tags:

r

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.

like image 775
Jstation Avatar asked Oct 21 '25 00:10

Jstation


1 Answers

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)]

data

set.seed(24)
df <- as.data.frame(matrix(rnorm(12 * 4), 4, 12))
like image 170
akrun Avatar answered Oct 22 '25 16:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!