1

Please help me with this I have a data table as below

    dt2 <- data.table(ID = c(1,1,2,2,3,3,4,4,4), variable =     c("a","b","a","c","c","d","e","b","a"))
    dt3 <- dt2[, list(variables = paste(variable, collapse = " | ")), by = ID]
    dt3[,chk:=sample(letters[1:2])]
    dt3
    ID variables chk
1:  1     a | b   b
2:  2     a | c   a
3:  3     c | d   b
4:  4 e | b | a   a

I want to filter records where variables contain chk. In the example above row 3 should be removed.

0

2 Answers 2

4

Here's an mapply approach. It takes the two parameters element by element in the operation:

dt3[mapply(grepl, x=variables, chk)]
#   ID variables chk
#1:  1     a | b   b
#2:  2     a | c   a
#3:  4 e | b | a   a
Sign up to request clarification or add additional context in comments.

Comments

1

We can use paste with grep

dt3[with(dt3, grep(paste(chk, collapse='|'), variables)),]
#     ID variables chk
#1:  1     a | b   a
#2:  2     a | c   b
#3:  4 e | b | a   b

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.