Krantz
Krantz

Reputation: 1493

Conditionally extract to a list variable values that appear in all columns

Given the sample data sampleDT below, I would appreciate any help to create a function that allows me to conditionally extract to a list without repetition the variable values that appear in all columns - at least appear once in each of the columns regardless of the position.

# sample data
sampleDT<-structure(list(V2 = c(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), 
    V3 = c(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 2), .indices = c(6, 
    7, 8, 9, 10, 11, 12, 13, 14, 15, 16), .indices3 = c(1, 2, 
    3, 4, 5, 6, 7, 8, 9, 10, 11)), row.names = c(NA, -11L), class = "data.frame")

Thanks in advance for any help.

Upvotes: 2

Views: 45

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

Reduce(f = intersect, x = sampleDT)
[1]  6  7  8  9 10 11

Use the intersect set operation on all the columns.

Reduce is a nice way to write intersect(intersect(sampleDT[[1]], sampleDT[[2]]), sampleDT[[3]]), ...))

Upvotes: 3

Related Questions