如何在 Gather TidyR 中引用多个独立变量?

How to Enquote Multiple independent vars in Gather TidyR?

我有这个数据集,我希望将其重塑为长格式:(更新 link)https://drive.google.com/file/d/1EqD58WVXm-v35Jr6GAwL6arxzO_tTyFa/view?usp=sharing

在手动重塑方法中,我是这样做的:

census_data <- read.csv(file.choose())
colnames(census_data)[8] <- "CENSUSPOP2010"
census_long <- census_data %>%
  gather(Var, Value, -SUMLEV, -REGION, -DIVISION, -STATE, -COUNTY, -STNAME, -CTYNAME) %>%
  mutate(Time = sub("[A-Za-z]+", "", Var), Type = sub("[\_0-9]+", "", Var)) %>%
  select(-Var) %>%
  spread(Type, Value)

但我希望引用独立变量,这样很容易将其传递给自定义函数,所以我不得不尝试这样定义它:

var <- c("SUMLEV", "REGION", "DIVISION", "STATE", "COUNTY", "STNAME", "CTYNAME")
var_enquos <- enquos(var)
census_long <- census_data %>%
  gather(Var, Value, -!!!var_enquos) %>%
  mutate(Time = sub("[A-Za-z]+", "", Var), Type = sub("[\_0-9]+", "", Var)) %>%
  select(-Var) %>%
  spread(Type, Value)

但这会产生:Error: Can't use !!! at top level.

难道这种方法都做不到?欢迎任何建议,谢谢

这是一种使用 pivot_longergather 的继承者)和“curly curly”运算符的方法,它完成了 enquo 和 !!一步到位。

var <- names(mtcars)[2:11]
var
# [1] "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"


library(tidyverse)
mtcars %>%
  pivot_longer(cols = {{ var }})


# A tibble: 320 x 3
     mpg name   value
   <dbl> <chr>  <dbl>
 1    21 cyl     6   
 2    21 disp  160   
 3    21 hp    110   
 4    21 drat    3.9 
 5    21 wt      2.62
 6    21 qsec   16.5 
 7    21 vs      0   
 8    21 am      1   
 9    21 gear    4   
10    21 carb    4   
# … with 310 more rows

或者如果你想坚持 gather:

mtcars %>% 
  gather("name", "value", {{ var }})

有关“curly curly”或“embrace”运算符的更多信息,这里有更多资源:

https://www.tidyverse.org/blog/2019/06/rlang-0-4-0/#a-simpler-interpolation-pattern-with-

https://sharla.party/post/tidyeval/

https://www.brodrigues.co/blog/2019-06-20-tidy_eval_saga/