Monique Plandsoen
Monique Plandsoen

Reputation: 3

in r drop columns in dataframe defined in a list using a for loop

I have a dataframe and I want to drop columns which are defined in a list.

First I have made a list of samples (which I want to keep) out of a excisting dataframe:

df_1 <- data.frame(sample = c("col1","col3"), gender = c("m","v"))
samplename <- list(df_1)

Then I want to drop the columns from another dataframe which are not in this list of samplenames:

test_df <- data.frame(col1 = c("a", "b", "c", "d", "e"), col2 = seq(1, 5), col3 = rep(3, 5), col4 = c("aa","bb","cc","dd","ee"))

for (col in colnames(test_df)){
     if (!(col %in% samplename[[1]])){
          test_df <- test_df[, col, drop = TRUE]
          }
     }

But this code is not working. What is a better way to perform this task? Where do I go wrong?

Upvotes: 0

Views: 46

Answers (2)

Martin Gal
Martin Gal

Reputation: 16978

Basically the same as Duck's answer:

library(dplyr)

test_df %>%
  select(!df_1$sample)

returns

  col2 col4
1    1   aa
2    2   bb
3    3   cc
4    4   dd
5    5   ee

Upvotes: 0

Duck
Duck

Reputation: 39595

You can try:

test_df[,!(names(test_df) %in% df_1$sample)]

  col2 col4
1    1   aa
2    2   bb
3    3   cc
4    4   dd
5    5   ee

Upvotes: 2

Related Questions