Home > Software design >  ?Error in "switch : EXPR must be a length 1 vector
?Error in "switch : EXPR must be a length 1 vector

Time:02-22

I am trying to assign the image channels back to RGB from 123. It shall be easy with switch(), but oddly, with totally identical cases, I assume, comes the different result: the DT2 gives right answer, and the DT1 gives error msg: Error in switch(cc, "A", "B", "C") : EXPR must be a length 1 vector

please find the toy examples, and thanks for the advice.

library(imager)
library(data.table)

DT1 <- setDT(as.data.frame(boats))[][, {
  RGB = switch(cc, "A", "B", "C")
  list(RGB=RGB)
}, by=value]

DT2 <- data.table(cc=1:3, value=1:6)[,{
     RGB = switch(cc, "A", "B", "C")
     list(RGB=RGB)
   }, by=value]

CodePudding user response:

EXPR has to be of length one. Try this:

setDT(as.data.frame(boats))[][, {
  RGB = sapply(cc, \(cc) switch(cc, "A", "B", "C"))
  list(RGB=RGB)
}, by=value]

or

setDT(as.data.frame(boats))[][, {
  RGB = c("A", "B", "C")[cc]
  list(RGB=RGB)
}, by=value]
  •  Tags:  
  • r
  • Related