• R语言已解决
  • 各位大神:咨询下如何在function里面select、group_by的时候使用字符串参数?

各位大神:
咨询下如何在function里面select、group_by的时候使用字符串参数?
我把批量画图的变量名写在一个dataframe中,然后希望批量调用并进行绘图。
使用eval(字符串),selecet工作了,但是后面的summarize的时候总是无法得到正确的数据。
相关参数在plotlist 中。

library(tidyfst)  # 
library(tidyverse)

Plot_string <- function( rate,fenmu,title,subtitle){
 p1 <- ds %>% 
    select( eval(rate),eval(fenmu)) %>% 
    as.data.table() #%>% 
    summarise_dt(rate_min=min(eval(rate)),by=eval(fenmu)) %>% 
  ggplot(aes_string( x=fenmu))+
  aes(y=rate_min)+
  geom_point(size=3)+
 geom_smooth(method = "glm")+
   labs(
  title = title,
   subtitle = subtitle
  )
  print(p1)
}

plotlist_dim <-plotlist %>% dim()  #plot写入了读取的相关变量等信息

for (m in 1:plotlist_dim[1]){
  
  Plot_rate_string(
    rate=plotlist[m,'rate'],
    fenmu=plotlist[m,'denominator'],
    title=plotlist[m,'title'],
    subtitle=plotlist[m,'subtitle']
  )

自定义函数中,需要使用到用户传入的字符串式的变量,字符串的值就是实际数据中的变量名,那么可以用.data[[var]]这样的写法。在select的时候可以用all_of(var)any_of(var)这样的形式,不需要采用eval

具体可以参考dplyr的文档 programming with dplyr

plumber 问题解决,多谢! 学习了。
感觉这样编程的思路有点绕,有点烧脑啊。