Nikhil Singh
Nikhil Singh

Reputation: 21

Select columns in a data frame with Negative Values

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

Answers (5)

geomicrobio
geomicrobio

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

AlexB
AlexB

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

Lucius Hu
Lucius Hu

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 columns

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

Here are some other ways :

  1. colSums :
data[colSums(data < 0) > 0]

#   x  y  z
#1 -2  2  1
#2  3  1 -5
#3  4 -5  6
  1. Filter :
Filter(function(x) any(x < 0), data)
  1. select from dplyr
library(dplyr)
data %>%  select(where(~any(. < 0)))
#select_if if you have older version
#data %>%  select_if(~any(. < 0))

Upvotes: 3

Nikhil Singh
Nikhil Singh

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

Related Questions