You want to do something like:
df[df[[col_name]] == value,]
then the function will be:
fun <- function(df, col_name, value) { df[df[[col_name]] == value,] } fun(x, 'col2', 'email') col1 col2 col3 2 search email 15
and if you want to take into account the NA values ββin a logical vector:
fun <- function(df, col_name, value) { logical_vector = df[[col_name]] == value logical_vector[is.na(logical_vector)] = FALSE df[logical_vector, drop = FALSE] }
Why does your example not work because the subset does not look inside the col value. Instead, it will look for a column called col . I suspect that the val parameter is also parsed incorrectly. This is one of the reasons not to use subset in non-interactive mode, that is, in everything except the interactive console R.
source share