R语言 Tidy eval在函数中失败

disbfnqx  于 2023-10-13  发布在  其他
关注(0)|答案(1)|浏览(121)

我试图自动化.tex表的生成,我想在stargazer的add.lines部分添加一个名为mean_outcome的值,但我在生成这个值时遇到了麻烦,我想我处理tidy eval时出错了。我已经试过了!”““但是什么都不起作用。

  1. df <- tibble::tribble(~hhid, ~treatment_arm, ~round_pooled, ~tot_lstock_count, ~tot_animal_tlu,
  2. "1020201023",1,1,10,1,
  3. "1020201023",1,11,6,0.600000023841858,
  4. "1020201036",1,1,10,0.100000001490116,
  5. "1020201036",1,11,4,0.400000005960464,
  6. "1020201039",1,1,9,0.0900000035762787,
  7. "1020201057",1,1,12,0.480000019073486,
  8. "1020201068",1,1,2,0.200000002980232,
  9. "1020201095",1,1,6,0.330000013113022,
  10. "1020201095",1,11,7,0.400000005960464,
  11. "1020201103",1,1,2,0.200000002980232,
  12. "1020201116",1,1,7,0.0599999986588955,
  13. "1020201116",1,11,2,0.0199999995529652,
  14. "1020201139",1,11,12,0.480000019073486,
  15. "1020201144",1,1,5,0.5,
  16. "1020201144",1,11,8,0.800000011920929,
  17. "1020201146",1,1,6,0.0599999986588955,
  18. "1020201146",1,11,6,0.0599999986588955,
  19. "1020201159",1,11,15,1.5,
  20. "1020201180",1,11,11,0.560000002384186,
  21. "1020201205",1,1,2,0.0199999995529652)
  22. reg_coef_tables <- function(df, y) {
  23. outcome = eval(`i`)
  24. mean_outcome <- df %>%
  25. filter(round_pooled == 11 & treatment_arm == 1) %>%
  26. summarise(mean = mean(!!outcome, na.rm = T)) %>%
  27. pull(mean)
  28. reg1 <- felm(outcome ~ treatment_arm, data = df)
  29. stargazer(reg1,
  30. align = TRUE,
  31. dep.var.labels = c("(1)"),
  32. omit.stat = c("f", "adj.rsq", "ser"),
  33. no.space = TRUE,
  34. digits = 3, # number of decimals
  35. add.lines = list(c('Mean outcome', rep(`mean_outcome`, 1)),
  36. dep.var.caption = "", # remove dep var header
  37. out = paste0(outcome, ".tex"))
  38. }
  39. liv_vars = c("tot_lstock_count", "tot_animal_tlu")
  40. liv_out_list = vector("list", 2)
  41. for(i in liv_vars) {
  42. liv_out_list[[i]] <- reg_coef_tables(df, i)
  43. }
vuktfyat

vuktfyat1#

撇开stargazer(因为,恕我直言,它很可怕)和felm(因为我不知道它来自哪个包),因为这两个都与tidyverse的问题无关,试试这个

  1. reg_coef_tables <- function(df, y) {
  2. outcome = as.name(y)
  3. mean_outcome <- df %>%
  4. filter(round_pooled == 11 & treatment_arm == 1) %>%
  5. summarise(mean = mean(!!outcome, na.rm = T)) %>%
  6. pull(mean)
  7. }
  8. liv_vars = c("tot_lstock_count", "tot_animal_tlu")
  9. liv_out_list = list()
  10. for(i in liv_vars) {
  11. liv_out_list[[i]] <- reg_coef_tables(df, i)
  12. }
  13. liv_out_list
  14. $tot_lstock_count
  15. [1] 7.888889
  16. $tot_animal_tlu
  17. [1] 0.5355556

或者,更简洁地说:

  1. mean_outcome <- df %>%
  2. filter(round_pooled == 11 & treatment_arm == 1) %>%
  3. summarise(
  4. across(
  5. c(tot_lstock_count, tot_animal_tlu),
  6. \(x) mean(x, na.rm = TRUE)
  7. )
  8. )
  9. mean_outcome
  10. # A tibble: 1 × 2
  11. tot_lstock_count tot_animal_tlu
  12. <dbl> <dbl>
  13. 1 7.89 0.536

你可以在NSE here上找到一个有用的引物。

展开查看全部

相关问题