Matthew Crews
Matthew Crews

Reputation: 4305

R data.table using median in i statement

This is a variation of the question on using the max() function in the i statement for filtering a data.table: R data.table using max in i statement

Now I'm trying to figure out how to use the median() function in the same situation. Here's my code that is returning every row:

> test_dt <- data.table(value1 = 1:10, value2 = 2:11, value3 = 3:12)
> test_dt[median(c(value1, value2, value3)) < 7]
    value1 value2 value3
 1:      1      2      3
 2:      2      3      4
 3:      3      4      5
 4:      4      5      6
 5:      5      6      7
 6:      6      7      8
 7:      7      8      9
 8:      8      9     10
 9:      9     10     11
10:     10     11     12

And here is what I expect to get if the median() function was operating on each row separately:

   value1 value2 value3
1:      1      2      3
2:      2      3      4
3:      3      4      5
4:      4      5      6
5:      5      6      7
6:      6      7      8

Upvotes: 1

Views: 103

Answers (1)

bartleby
bartleby

Reputation: 107

Here is an solution using data.table::transpose (twice, so its not unconvoluted):

test_dt[transpose(transpose(test_dt)[,lapply(.SD,median)])[[1]] <7]

Upvotes: 1

Related Questions