0

I have this dataset that I wish to reshape to long format.

In manual approach of reshaping, I do it with this:

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)

But I wish that the independent vars are quoted, so it is easy to pass it to custom functions, so I had to try to define it like this:

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)

But this produces: Error: Can't use !!! at top level.

Is this approach not possible to do?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jovan
  • 763
  • 7
  • 26

1 Answers1

3

Here's an approach using pivot_longer (the successor to gather) and the "curly curly" operator, which accomplishes the enquo and the !! in one step.

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

Or if you want to stick with gather:

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

For more on the "curly curly" or "embrace" operator, here are more resources:

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 Tidy evaluation and modifying inputs or their names

Jon Spring
  • 55,165
  • 4
  • 35
  • 53