The subset is based on the set of function arguments

I am new to writing functions, so hopefully below makes sense.

I want to create a function that takes some arguments that will be used for a subset of data.frame. I searched the forums and found these Q & As interesting, but could not answer my question from the discussions:

The function I want to create will take the name df, the column name and the value that will match in the column name strings. Here is my attempt, which I see wrong:

x <- data.frame("col1"=c("email","search","direct"), "col2"=c("direct","email","direct"), "col3"=c(10,15,27)) fun <- function(df,col,val) { result <- subset(df, col==val) return(result) } 

I want to pass in df, x. The name of the column is, say, "col2". Meaning, say, "email". My attempt to do this returns df of length df.

 fun(x,"col2","email") 

It’s clear that I am doing something wrong ... can anyone help?

+4
source share
1 answer

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.

+3
source

Source: https://habr.com/ru/post/1485411/


All Articles