r - 如何将`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
?
解决方案
这是我要做的:
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
推荐阅读
- java - DateTimeFormatter.ofPattern 语言选项
- hadoop - 在 ec2 实例上运行 MissingPokerCards 时出现 ClassNotFoundException
- python - 超过字符数时值更改
- haskell - 当后一位数字大于haskell中的前一位数字时中断
- python - 使用来自 db 的计数用于使用 pandas 的 matplotlib 条形图?
- r - 来自ggimage的geom_image任意选择纵横比
- firebase - 在 DataTable 中显示带有颤动的 Firestore 数据
- tensorflow - 如何加快word2vec相似度计算?
- verilog - 简单的加法器 + 测试台返回“不关心”输入
- python - 在没有优化函数的情况下,在 Python 中寻找不等式系统的解决方案