I am having difficulty getting around this issue of needing to pass a df and colname to a function. Calling that assigned colname variable within a tidy pipe calls the error https://tidyselect.r-lib.org/reference/faq-external-vector.html but the use of all_of() does not work in this instance.
Context: I am passing singular excel sheets to the function and each sheet has a different title for the first column. So I need to pass the column name as an external variable to the function, then within the function to a tidy pipe to pivot.
Pass a data.frame column name to a function The link here discusses the first issue, passing column name to function and I am using the deparse(substitute) method. But the problem is arising as part of tidyverse I'm pretty sure. I just can't see a way around this?
totals <- tibble::tribble(
~Units, ~NACE, ~"1990", ~"1991", ~"1992", ~"1993", ~"1994", ~"1995", ~"1996", ~"1997", ~"1998",
"Imports", 0, 4155, 5145, 7355, 6155, 4715, 4155, 4155, 4155, 4155,
"Exports", 0, 3952, 3952, 3952, 3952, 3952, 3952, 3952, 3952, 3952,
"X", 14, 99598, 99598, 99598, 99598, 99598, 99598, 99598, 99598, 99598,
"Y", 16, 6260, 6260, 6260, 6260, 6260, 6260, 6260, 6260, 6260,
"Z", 8, 36583, 36583, 36583, 36583, 36583, 36583, 36583, 36583, 36583,
)
# ---- reshape data ----
reshape_data <- function(data, colname){
main <- totals %>%
select(!NACE)
new_col <- main %>%
pivot_longer(!{{colname}}, names_to = "Year", values_to = "Total Supply") %>%
rename(`Total.Units` = {{colname}})
}
data <- (totals, "Units") # or colname = "Units", neither work
Error in pivot_longer()
:
! Can't subset columns that don't exist.
✖ Column "Units"
doesn't exist.
Any ideas how to approach this task?
As suggested by Zé Loff in comments above, using pivot_longer(-1) worked.
Suggestion by Jon Spring to wrap colname in {{}} also works;
reshape_data <- function(data, colname){data %>%
select(!NACE) %>%
pivot_longer(!{{colname}}, names_to = "Year",
values_to = "Total Supply") %>%
rename('Total.Units' = {{colname}}) };
reshape_data(totals, Units)