2

How can I remove every column that meets a specific condition from a specific row? In my case remove each column with =="-" in the first row.

I want to do it completely inside [ ] without copying the data in memory, and if possible avoiding an external function.

mtcars[1,c(2,4,6)] <- "-"
dt <- data.table(mtcars)

didn't work:

temp[,.SDcols := function(x) x[1]!="-"]
temp[,.SD:= .SDcols = (function(x) x[1]!="-")]

works but copies the data:

temp[ , .SD, .SDcols = function(x) x[1]!="-"]

there are other posts about this topic but my question is different because none of these posts show how to subset before looking for a condition inside the [ ]

delete column in data.table in R based on condition

Removing multiple columns from R data.table with parameter for columns to remove

MLavoie
  • 9,671
  • 41
  • 36
  • 56

2 Answers2

2

You could drop the columns containing "-" in the first rows by reference as follows:

dt[, which(c(dt[1]=="-")) := NULL]
1

How about this?

 dt[,dt[1]!="-", with=FALSE]
LocoGris
  • 4,432
  • 3
  • 15
  • 30