student_R123
student_R123

Reputation: 1002

Creating a function to get a two way table using R

I have following data:

require(dplyr)
x1=rbinom(1000,1,prob = 0.6)
x2=rbinom(1000,2,prob = c(0.3,0.4,0.3))
data=data.frame(x1,x2)

Then I need to cross tabulate the data where x2=2.

I used the dplyr function to get the desired results as follows:

data %>% filter(x2==2) %>% count(x1,x2)
  x1 x2  n
1  0  2 38
2  1  2 71

This is one of the single operation that I am performing to data. Also I need to do this multiple times. So, I tried to create a function to get the same results as follows:

fun1=function(data,text1,text2)
{
  return(data %>% filter({{text2}}==2) %>% count({{text1}},{{text2}}))
}
fun1(data,"x1","x2")

But I am not getting the desired results. Will anybody help me to figure out what am I doing wrong?

Thank you!!

Upvotes: 1

Views: 38

Answers (1)

the-mad-statter
the-mad-statter

Reputation: 8711

You have written your function to use non-standard evaluation (NSE) so use it when calling your function as well. That is do not pass the arguments as characters with quotes. Do this instead:

fun1(data, x1, x2)

#   x1 x2  n
# 1  0  2 41
# 2  1  2 74

Upvotes: 2

Related Questions