SaikiHanee SaikiHanee - 4 months ago 9
R Question

subset a dataframe using condition passed as string (subset dataframe dynamically)

We can retrieve a subset of data-frame

df
where
col1
's value is equal to 1 using the following code.

sub = df[df$col1==1,]


I want to subset a data-frame based on some conditions which are passed as strings

cond = "df$col1==1"
sub = df[cond, ]


The above code doesn't work. Is there any work around to achieve this? How to subset data-frame dynamically?

Answer

Try:

cond = "df$col1==1"
sub = df[eval(parse(text=cond)),]

Thanks!