bic ton
bic ton

Reputation: 1408

Remove a column with positive values?

I have data:

structure(c(1.44, 0.28, 1.7, 0.4, 0.03, -0.61, 0.33, 
-0.84), .Dim = c(4L, 2L), .Dimnames = list(c("19", 
 "10", "20", "1"), c("A", "B")))

Remove the column with values are all positive. Here A should be removed.

Upvotes: 2

Views: 93

Answers (3)

akrun
akrun

Reputation: 887951

Another option using sum

library(dplyr)
as.data.frame(df) %>% 
     select_if(~ sum(. < 0) > 0)

Upvotes: 1

Rahul Podi Rajagopal
Rahul Podi Rajagopal

Reputation: 41

Using apply: Considering df as the dataframe in which your columns are present, the below command should work

df [ , apply(df, 2, function(x) length(which( x < 0 ))) > 0]

A small explanation of the above function

  • First argument of the apply function is the dataset (df) on which you need to apply a logic
  • The second argument takes 1 (or) 2 where 1 corresponds to perform operations at a row level and 2 corresponds to perform operations at a column level (here what you needed was column level operations)
  • The third argument takes the function needed to perform, in case of in-built functions (lets say sum) then function(x) as in the above code is not needed

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

Using colSums :

df[, colSums(df < 0) > 0, drop = FALSE]

#      B
#19  0.03
#10 -0.61
#20  0.33
#1  -0.84

Or using apply :

df[, apply(df < 0, 2, any), drop = FALSE]

If you convert data into dataframe, you can also use :

Filter(function(x) any(x < 0),  as.data.frame(df))

Or with dplyr :

as.data.frame(df) %>% select_if(~any(. < 0))

Upvotes: 2

Related Questions