首页 > 解决方案 > 如何将`c(a,b)`转换为`table(a,b)`的参数?

问题描述

我需要编写函数vec_to_para,当我运行时 vec_to_para(c('vs','gear'),mtcars),应该输出with(mtcars,table(vs,gear)).

我昨天问了一个类似的问题,然后我尝试了paste()

#expected result
> with(mtcars,table(vs,gear))
   gear
vs   3  4  5
  0 12  2  4
  1  3 10  1

#my function,where is the problem?
>vec_to_para<-function(vec,df){
    with(df,tables(paste(vec,collapse=',')))
}

#run to test function
>vec_to_para(c('vs','gear'),mtcars)
vs,gear 
      1 

功能问题出在哪里vec_to_para

标签: r

解决方案


这是我要做的:

vec_to_para<-function(vec,df) {
  table(df[vec])
}

vec_to_para(c("vs", "gear"), mtcars)
   gear
vs   3  4  5
  0 12  2  4
  1  3 10  1

但是,使用get()您可以使您当前的解决方案以最少的修改工作:

vec_to_para<-function(vec,df) {
  with(df, table(get(vec[1]), get(vec[2])))
}

vec_to_para(c("vs", "gear"), mtcars)

     3  4  5
  0 12  2  4
  1  3 10  1

推荐阅读