0

My code is like this:

     fcase(V2009 == 9L & V3006 == 2L, V1032,
        V2009 == 10L & V3006 == 3L, V1032,
        V2009 == 11L & V3006 == 4L, V1032,
        V2009 == 12L & V3006 == 5L, V1032,
        V2009 == 13L & V3006 == 6L, V1032,
        V2009 == 14L & V3006 == 7L, V1032,
        V2009 == 15L & V3006 == 8L, V1032,
        V2009 == 16L & V3006 == 9L, V1032,
        V2009 == 17L & V3006 == 10L, V1032,
        default = NA_integer_)

I thought it would look better inside a loop, for example:

fcase(for(i in 9L:17L){
      for(j in 2L:10L){
      V2009 == i & V3006 == j, V1032}}, default = NA_integer_ )

Of course this way the code wont run, but is there any?

  • You could change it to `fcase(paste(V3006, V2009) %in% paste(2:10, 2:10 + 7) ~ V1032, default = NA_integer_)` – akrun Apr 28 '21 at 21:30
  • It would be easier to help if you create a small reproducible example along with expected output. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Apr 29 '21 at 03:44

2 Answers2

1

As the conditions follow a pattern, instead of writing multiple expressions, paste the columns/objects together along with values to match and use %in%

library(data.table)
fcase(paste(V3006, V2009)  %in% paste(2:10, 2:10 + 7), V1032, 
          default = NA_integer_)

Using fifelse with for loop

v1 <- 2L:10L
v2 <- 9L:17L
out <- rep(NA_integer_, length(V1032))
for(i in seq_along(v1)) out <- fifelse(V2009 == v2[i] &
          V3006 == v1[i], V1032, out)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You can make a bunch of lists and then use do.call to piece together all the inputs to fcase:

Example data:

dat <- data.table(V2009 = 6:10, V3006 = 5:1, V1032=rep(1L,5))

Longhand:

dat[,
  fcase(
    V2009 == 9L & V3006 == 2L, V1032,
    V2009 == 10L & V3006 == 3L, V1032,
    default = NA_integer_
  )
]
#[1] NA NA NA  1 NA

do.call shorthand:

dat[, do.call(fcase, rbind(Map(
  function(i,j) V2009 == i & V3006 == j, 9:17, 2:10), .(V1032))) ]
#[1] NA NA NA  1 NA
thelatemail
  • 91,185
  • 12
  • 128
  • 188