San
San

Reputation: 568

How to check whether integer values in a list column in a data.table fall within a specified range

Suppose there is a data.table as under:

exp <- structure(list(
  id = c("a", "b"),
  num = list(c(2L, 5L, 8L),
              c(6L, 10L, 13L, 19L))),
  .Names = c("id", "num"),
  row.names = c(NA, -2L),
  class = c("data.table", "data.frame"))

See it:

exp
   id         num
1:  a       2,5,8
2:  b  6,10,13,19

The structure:

str(exp)
Classes ‘data.table’ and 'data.frame':  2 obs. of  2 variables:
 $ id : chr  "a" "b"
 $ num:List of 2
  ..$ : int  2 5 8
  ..$ : int  6 10 13 19

My task is to create a new column (say, bw_1_to_5) which tells me whether the num column contains any number between 1 to 5. So the first row should show TRUE and second row should show FALSE.

I tried using mapply, %in%, intersect and any but could not get it right. Any help would be appreciated.

Upvotes: 1

Views: 132

Answers (1)

akrun
akrun

Reputation: 886948

We can loop through the list column, check if there is any value in the 1:5 range and assign := to new column

exp[, bw_1_to_5 := unlist(lapply(num, function(x) any(1:5 %in% x)))]
exp
#   id         num bw_1_to_5
#1:  a       2,5,8      TRUE
#2:  b  6,10,13,19     FALSE

If we use the map from purrr, this can be further concised to

library(purrr)
exp[, bw_1_to_5 := map_lgl(num, ~ any(1:5 %in% .x))]

Upvotes: 1

Related Questions