luca tucciarone
luca tucciarone

Reputation: 111

Subsetting dataframe threshold based on X values greater or lower than Y

I need to subset a dataset based on X values greater or lower than Y . For example, given a dataset:

col1 <- c(1,2,3,4)
col2 <- c(1,2,-1,4)
col3 <- c(1,2,-3,-4)
df <- cbind(col1,col2,col3,col_Reference)
df
     col1 col2 col3 
[1,]    1    1    1 
[2,]    2    2    2 
[3,]    3   -1   -3 
[4,]    4    4   -4

Let's say I want to keep the row only if there is at least 1 value greater than 3 or lower than 3. I should get something like this:

     col1 col2 col3
[2,]    3   -1   -3      
[3,]    4    4   -4 

Thanks a lot

Upvotes: 2

Views: 44

Answers (2)

akrun
akrun

Reputation: 886948

We can use pmax

df[do.call(pmax, abs(as.data.frame(df))) >=3,]
#     col1 col2 col3
#[1,]    3   -1   -3
#[2,]    4    4   -4

data

df <- cbind(col1 = 1:4, col2 = c(1, 2, -1, 4), col3 = c(1, 2, -3, -4))

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 269451

Check maximum absolute value and compare to 3:

df[apply(abs(df), 1, max) >= 3, ]
##      col1 col2 col3
## [1,]    3   -1   -3
## [2,]    4    4   -4

Upvotes: 3

Related Questions