Reputation: 1408
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
Reputation: 887951
Another option using sum
library(dplyr)
as.data.frame(df) %>%
select_if(~ sum(. < 0) > 0)
Upvotes: 1
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
Upvotes: 1
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