Given a dataset (let say stored as data frame) in the form:
> n <- 10
> set.seed(123)
> ds.df <- data.frame(col1 = round(rnorm(n,2,4), digit = 1),
col2 = sample.int(2, n, replace = TRUE),
col3 = sample.int(n*10, n),
col4 = sample(letters, n, replace = TRUE))
is there a simple and efficient way to subset it, using a vector of value that defines multiple equalities the subset should respect? Something like:
> subset_v <- c(col1 = -0.2, col4 = "i")
> ds.subset <- subset(ds.df, subset_v)
> ds.subset
col1 col2 col3 col4
1 -0.2 1 9 i
where the function subset(ds.df,subset_v) should return the subset that respect:
ds.df[ ds.df$col1 == subset_v["col1"] & ds.df$col2 == subset_v["col2"] & ds.df$col4 == subset_v["col4"], ]
But this last expression isn't very handy and I would like to be able to have any column without knowing them into advance.
I did something that works:
subset <- function(ds.df,subset_v){
sub = rep(TRUE, nrow(ds.df))
for(cn in names(subset_v)){
sub=sub & (ds.df[,cn] == subset_v[[cn]])
}
ds.df[sub,]
}
But I feel like there is a much better and more efficient way to do it (maybe removing the for loop somehow).