user35131
user35131

Reputation: 1134

How to remove columns in a dataframe in R based on the values from another vector?

I have a list of values in a vector that i would like to use in deleting the columns found in a dataframe.

For example if my data frame has columns A,B,C,D,E,F,G,H

and my vector has values of C,E,H

i would like my data frame to have columns

A,B,D,F,G,

Upvotes: 1

Views: 634

Answers (1)

akrun
akrun

Reputation: 887028

There are different options. If we want to remove from the original dataset, assigning to NULL is quick

df1[vecofnames] <- NULL

Another option if we want to subset it to a different object

df2 <- df1[setdiff(names(df1), vecofnames)]

Or with subset

df2 <- subset(df1, select = -vecofnames)

Or in dplyr

library(dplyr)
df2 <- df1 %>%
         select(-vecofnames)     

Upvotes: 2

Related Questions