learningr
learningr

Reputation: 11

Find which rows in a data frame have negative values?

I have a data frame called y and I want to know exactly which rows have at least one negative number so I can select those rows of y and inspect them myself. I tried a few different ways but they gave me strange results so I ended up writing the following for loop:

temp <- NULL
# Check for negative values
for(i in 1:nrow(y)) {
  for(j in 1:length(y)) {
    if(y[i,j] < 0) {
      temp[i] <- i
    }
  }
}
na.omit(temp)

This gave me what I wanted, but I'm pretty sure there's an easier way to code that. Maybe using apply or lapply or something else. Can anyone help me find more efficient code that gives me the row numbers of the rows that have at least one negative value? To be clear, I want the row numbers only

Upvotes: 0

Views: 1559

Answers (2)

GuedesBF
GuedesBF

Reputation: 9858

You can use dplyr with rowwise() and rowSums():

creating toy dataframe:

df<-data.frame(a=c(2,6,0,8), b=c(2,7,5,0), c=c(1,0,2,8), d=c(4,3,8,5))
> df
  a b c d
1 2 2 1 4
2 6 7 0 3
3 0 5 2 8
4 8 0 8 5

solution with base R using apply() with MARGIN=1:

df$has_negatives<-apply(df, 1, function(x) any(x<0))
df
  a b c d has_negatives
1 2 2 1 4     FALSE
2 6 7 0 3      TRUE
3 0 5 2 8      TRUE
4 8 0 8 5      TRUE

Solution with dplyr:

df%>%rowwise()%>%mutate(has_negatives=rowSums(across(everything(), ~(.<0))))
# A tibble: 4 x 5
# Rowwise: 
      a     b     c     d has_negatives
  <dbl> <dbl> <dbl> <dbl>     <dbl>
1     2     2     1     4         0
2     6     7     0     3         1
3     0     5     2     8         1
4     8     0     8     5         1

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101327

You can try which like below

which(y<0,arr.ind = TRUE)

Upvotes: 2

Related Questions