Optimize code to filter R dataframe -


i have r code takes in args string command line , filters dataframe based on values in column; args string contains column names. right i'm doing looping through vector tells me there has better way. there way optimize code?

args = c("col1","col2") for(i in args){   df = df[df[,i]==0,] } 

if understand correctly, want keep rows of args equal 0 (or other given value).

first indices of columns you're interested in:

idx <- match(args, colnames(df)) 

then can do:

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

another possibility:

df <- df[rowsums(df[, idx] != 0) == 0, ] 

Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -