I am trying to write a function that sets the default for some arguments to NULL. However, when I then want to specify those arguments to not be NULL when calling the function, I receive the error that those objects cannot be found.
Simple starter function:
library(dplyr)
toydf <- data.frame(Name = "Fred", Age="Old", Hair="Brown")
toyA <- function(df, groupA){
data.frame(A = df%>%dplyr::select({{groupA}}))
}
toyA(toydf, Name)
toyA(toydf, Age)
I want to specify some arguments to have a NULL default, which this and this seem to suggest should work. I try this:
toyB <- function(df, groupA, groupB=NULL, groupC=NULL){
if((!is.null(groupB)) & (!is.null(groupC))){
data.frame(A = df%>%dplyr::select({{groupA}}),
B = df%>%dplyr::select({{groupB}}),
C = df%>%dplyr::select({{groupC}}))
}
else{
data.frame(A = df%>%dplyr::select({{groupA}}))
}
}
But this throws me the error:
toyB(toydf, Name, Age, Hair)
Error in toyB(toydf, Name, Age, Hair) : object 'Age' not found
We can work around it by checking missing() as some other questions and solutions suggest.
toyC <- function(df, groupA, groupB, groupC){
if((!missing(groupB)) & (!missing(groupC))){
data.frame(A = df%>%dplyr::select({{groupA}}),
B = df%>%dplyr::select({{groupB}}),
C = df%>%dplyr::select({{groupC}}))
}
else{
data.frame(A = df%>%dplyr::select({{groupA}}))
}
}
toyC(toydf,Name)
toyC(toydf, Name, Age, Hair)
Why is it that the NULL default is not working?
is.null(groupB), which resolves tois.null(Age), and then can't find an objectAgeto check (because it's a column of the dataframe).is.null(GroupB)you are evaluating the promise that points toAgeand that variable doesn't exist at the time you are checkingis.null, it only exists in the data.frame. The dup shows you how to avoid the early evaluation.