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
Post a Comment