How to Remove Rows with 0 Values Using R

How to remove rows with any zero value

There are a few different ways of doing this. I prefer using apply, since it's easily extendable:

##Generate some data
dd = data.frame(a = 1:4, b= 1:0, c=0:3)

##Go through each row and determine if a value is zero
row_sub = apply(dd, 1, function(row) all(row !=0 ))
##Subset as usual
dd[row_sub,]

remove R Dataframe rows based on zero values in one column

Just subset the data frame based on the value in the No_of_Mails column:

df[df$No_of_Mails != 0, ]

Demo

Remove rows in a dataframe if 0 is found X number of times

Here is a one-liner. Note that rowSums is coded in C and is fast.

df[!rowSums(df == 0) >= 2, , drop = FALSE]

How to remove rows with 0 in numeric columns in R

Here is a way that keeps only the columns with no values less than or equal to zero.

keep <- sapply(fish_data, function(x) {
if(is.numeric(x)) all(x > 0) else TRUE
})
fish_data[keep]
## A tibble: 6 x 7
# Species WeightGRAM VertLengthCM DiagLengthCM CrossLengthCM HeightCM WidthCM
# <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 Bream 242 23.2 25.4 30 11.5 4.02
#2 Bream 290 24 26.3 31.2 12.5 4.31
#3 Bream 340 23.9 26.5 31.1 12.4 4.70
#4 Bream 363 26.3 29 33.5 12.7 4.46
#5 Bream 430 26.5 29 34 12.4 5.13
#6 Bream 450 26.8 29.7 34.7 13.6 4.93

remove row if there are zeros in 2 specific columns (R)

We can use rowSums to create a logical vector. i.e. subset the first two columns of 'mk', check if it is equal to 0, get the rowSums of logical matrix and convert to a logical vector with < 2, use that as row index to subset the rows

mk[rowSums(mk[, 1:2] == 0) < 2,]
# col1 col2 col3 col4
#row1 1 0 6 7
#row2 5 7 0 6

Or using apply

mk[!apply(mk[, 1:2]==0, 1, all),]
# col1 col2 col3 col4
#row1 1 0 6 7
#row2 5 7 0 6

Or with any

mk[apply(mk[, 1:2], 1, any),]

data

mk <- structure(c(1L, 5L, 0L, 0L, 7L, 0L, 6L, 0L, 4L, 7L, 6L, 6L), 
.Dim = 3:4, .Dimnames = list(
c("row1", "row2", "row3"),
c("col1", "col2", "col3", "col4"
)))

How to remove rows where all columns are zero using data.table

You can try with rowSums -

library(data.table)
setDT(dat)
dat[rowSums(dat != 0) != 0]

# a b c
#1: 0 1 0
#2: 2 0 1
#3: 3 0 3

How to remove rows with 0 values using R

df[apply(df[,-1], 1, function(x) !all(x==0)),]


Related Topics



Leave a reply



Submit