Create a new variable showing names of columns matching a certain value in data.table r

18 Views Asked by At

I want to create a new variable that shows the names of columns within a defined vector , which are matching a certain row value in data table R.


my_data_table <- data.table(
  Column1 = c(1, 2, 3, 4, 5, 6),
  Column2 = c("A", "B", "C", "D", "E", "F"),
  Column3 = c(10.5, 20.3, 15.7, 30.2, 45.1, 12.8),
  Column4 = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE),
  Column5 = c("X", "Y", "Z", "W", "V", "U"),
  Column6 = c(100, 200, 150, 300, 450, 120)
)

vector <- c(Column1,Column2,Column3)

I tried using a couple of codes including ifelse function like this:

my_data_table[,NV := lapply(.SD, function(x) {
  ifelse(any(x == "value"), names(.SD)[which(x == "value")], NA)
}), .SDcols = "vector"]

I got it from ChatGBT and it throws the following error: Supplied 7 items to be assigned to 35 items of column 'NV'.

0

There are 0 best solutions below