Reputation: 21
How to select columns in data frame with negative values. For below data frame, want to select column x, y and z
data <- data.frame(x = c(-2,3,4), y = c(2,1,-5), z = c(1,-5,6), a = c(1,2,3))
Upvotes: 1
Views: 1947
Reputation: 350
You can do a vector with the colnames which contain negative values and then select them, example:
library(tidyverse)
# Dataset demo
data <- data.frame(
letter=c("A", "b", "c", "d", "e"),
positive=c(.26,.25,.36,.11,.35),
negative=c(12,15,-1,-10,-12)
)
# Vector with colnames with negative values
vector_negative <- colnames(data)[colSums(data < 0)]
# Select from de dataframe
data %>%
select(all_of(vector_negative))
Output:
negative
1 12
2 15
3 -1
4 -10
5 -12
Upvotes: 0
Reputation: 3269
Another way would be:
data[, sapply(1:ncol(data), function(i) any(data[, i] < 0))]
or to use purrr
:
data %>% purrr::keep(~any(. < 0))
data %>% purrr::discard(~!any(. < 0))
which will yield:
# x y z
# 1 -2 2 1
# 2 3 1 -5
# 3 4 -5 6
Upvotes: 1
Reputation: 307
data[apply(data, 2, function(col) any(col < 0))]
any(expr)
returns true when the expr
holds true for any element in a vector/list.apply(x, margin, fun)
, where margin = 2
means vectorise over columnsUpvotes: 0
Reputation: 388982
Here are some other ways :
colSums
:data[colSums(data < 0) > 0]
# x y z
#1 -2 2 1
#2 3 1 -5
#3 4 -5 6
Filter
:Filter(function(x) any(x < 0), data)
select
from dplyr
library(dplyr)
data %>% select(where(~any(. < 0)))
#select_if if you have older version
#data %>% select_if(~any(. < 0))
Upvotes: 3
Reputation: 21
One way of doing this is using sapply and apply functions in R
x<- data[!sapply(apply(data, 2, function(w){ if(min(w)<0) return(list(w)) }), is.null)]
names(x)
Feel free to suggest other ways of doing so
Upvotes: 1