0

我有这个数据集,我希望将其重塑为长格式:(更新链接)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.

难道这种做法都不可能吗?欢迎任何建议,谢谢

4

1 回答 1

3

这是一种使用pivot_longer(的继承者gather)和“卷曲”运算符的方法,它完成了 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 }})

有关“卷曲”或“拥抱”运算符的更多信息,请参阅以下资源:

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/

curly curly 整洁的评估和修改输入或其名称

于 2021-04-29T05:12:39.423 回答