Blazej Krzeminski
2009-Jun-24 12:16 UTC
[R] subsetting data frame using a vector of column names / values
Hello I have a data frame d with columns "var1", "var2", "var3" Then I have two vectors: columns <- c("var2", "var3") values <- c(0, 1) Is there a compact way to subset the data frame using these two vectors and get the result equivalent to: select (d, var2==0 & var3==1) ? Thank You Blazej
Henrique Dallazuanna
2009-Jun-24 12:42 UTC
[R] subsetting data frame using a vector of column names / values
Try this: subset(d, eval(parse(text = paste(paste(columns, values, sep = "=="), collapse = " & ")))) On Wed, Jun 24, 2009 at 9:16 AM, Blazej Krzeminski <bkrzem@gmail.com> wrote:> Hello > > I have a data frame d with columns "var1", "var2", "var3" > > Then I have two vectors: > columns <- c("var2", "var3") > values <- c(0, 1) > > > Is there a compact way to subset the data frame > using these two vectors and get the result equivalent to: > > select (d, var2==0 & var3==1) ? > > Thank You > > Blazej > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]]
Petr PIKAL
2009-Jun-24 13:06 UTC
[R] Odp: subsetting data frame using a vector of column names / values
Hi r-help-bounces at r-project.org napsal dne 24.06.2009 14:16:15:> Hello > > I have a data frame d with columns "var1", "var2", "var3" > > Then I have two vectors: > columns <- c("var2", "var3") > values <- c(0, 1) > > > Is there a compact way to subset the data frame > using these two vectors and get the result equivalent to: > > select (d, var2==0 & var3==1) ?The first part, to select columns seems to be straightforward d[,columns] the second part is a bit trickier e.g. ind = which(rowSums(mapply("%in%", d[,columns], values))>1) d[ind, columns] shall give you the result Regards Petr> > Thank You > > Blazej > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html> and provide commented, minimal, self-contained, reproducible code.