I'm trying to write a function, using dplyr
syntax, which includes grouping with group_by inside the function. There seems to be a problem with the group_by
statement, and I can't figure out whats wrong. When I pass abc
as an argument and using select
inside the function, it works as i would have expected (Gfunc1). When trying to group_by
the same argument, it gives me an error;
Error: Column
dims
is unknown
Please see exampel below. I really hope I have not overlooked some embarrassingly simple thing... anyway, would be gratefull for help!
library(dplyr)
abc <- c("a","a","a","b","b","c")
num <- c(1,2,3,4,5,6)
df <- data.frame(abc,num)
Gfunc1 <- function(dims) {
test1 <- df %>%
select(dims)
assign("test1", test1, envir = .GlobalEnv)
}
Gfunc2 <- function(dims) {
test2 <- df %>%
group_by(dims)
assign("test2", test2, envir = .GlobalEnv)
}
Gfunc1("abc")
# Returns as expected; df test1 with only col = "abc"
Gfunc2("abc")
# Does not return what i expect; gives error: Error: Column `dims` is unknown