0

I have 2 dataframes,

df1 <- data.frame(a = c(1,2,3,4,9), b = c(1,2,3,4,5) , c = c(1,2,3,4,9), d = c(1,2,3,4,5) )

df2 <- data.frame( c = c(1,2,3,4,5) ,a = c(1,2,3,4,5) )

I want to drop all column names of df2 from df1

Something like that below (but not working)

df1[, -colnames(df2)]
M--
  • 25,431
  • 8
  • 61
  • 93
determinator
  • 129
  • 1
  • 1
  • 5
  • 1
    Does this answer your question? [Drop data frame columns by name](https://stackoverflow.com/questions/4605206/drop-data-frame-columns-by-name) – holzben Dec 07 '20 at 18:29

2 Answers2

1

using %in% can do the job:

df1 <- df1[, !colnames(df1) %in% colnames(df2)]
holzben
  • 1,459
  • 16
  • 24
0

A tidyverse solution. The select function from dplyr allows you to select or omit columns by name or index number. You can use the - operator to omit.

require(tidyverse)
require(magrittr)
df1 <- data.frame(a = c(1,2,3,4,9), b = c(1,2,3,4,5) , c = c(1,2,3,4,9), d = c(1,2,3,4,5) )
df2 <- data.frame( c = c(1,2,3,4,5) ,a = c(1,2,3,4,5) )
df1 %<>% select(-colnames(df2))
J Thompson
  • 144
  • 5