5

In R, one can easily drop columns from a data frame according to name pattern: see How to drop columns by name pattern in R? and Subset data to contain only columns whose names match a condition, for example.

> df <- data.frame(A=c(1,2,3), A2=c(1,2,3), B=c(1,2,3), BG=c(2,2,3))
> df[, -grep("A", colnames(df))]
  B BG
1 1  2
2 2  2
3 3  3

But directly applying the solutions to a data.table doesn't work.

> dt <- data.table(A=c(1,2,3), A2=c(1,2,3), B=c(1,2,3), BG=c(2,2,3))
> dt[, -grep("A", colnames(df))]
[1] -1 -2

What can be done?

Community
  • 1
  • 1
wwl
  • 2,025
  • 2
  • 30
  • 51

1 Answers1

5

As Rich Scriven points out, dt[, grep("A", names(dt)) := NULL] works.

> dt <- data.table(A=c(1,2,3), A2=c(1,2,3), B=c(1,2,3), BG=c(2,2,3))
> dt[, grep("A", names(dt)) := NULL]
> dt

   B BG
1: 1  2
2: 2  2
3: 3  3
wwl
  • 2,025
  • 2
  • 30
  • 51