I am trying to make a function with optional arguments. As of now the function works if all arguments are specified, but it breaks down when I leave one of the optional arguments out.
Here are the test data.tables:
library("data.table")
set.seed(2018)
ref_test_dt = data.table(FV = c(50000,sample((100:10000), 40, replace = T)),
msd = c(sample(1:100,41,replace = T)),
Product = c(rep("Cards",5),rep("Loans",36)))
target_test_dt = data.table(FV = c(70000,65800,sample((100:10000), 20, replace = T)),
msd = c(sample(1:100,22,replace = T)))
my function:
scatter_test_f = function(x, y, target = NULL, ref = NULL){
x = deparse(substitute(x))
y = deparse(substitute(y))
if (!is.null(ref)){
ref_compress = ref[, .(ref[[x]], ref[[y]])]
setnames(ref_compress,c("V1","V2"),c(x, y))
ref_add = ref_compress[, c("countlines", "Dataset") := .(1, "Reference")]
ref_add[]
}
else if (!is.null(target)){
target_compress = target[, .(target[[x]], target[[y]])]
setnames(target_compress,c("V1","V2"),c(x, y))
target_add = target_compress[,c("countlines", "Dataset") := .(1, "Target")]
target_add[]
}
else
target_compress = target[, .(target[[x]], target[[y]])]
setnames(target_compress,c("V1","V2"),c(x, y))
target_add = target_compress[,c("countlines", "Dataset") := .(1, "Target")]
ref_compress = ref[, .(ref[[x]], ref[[y]])]
setnames(ref_compress,c("V1","V2"),c(x, y))
ref_add = ref_compress[, c("countlines", "Dataset") := .(1, "Reference")]
ggData = rbind(target_add, ref_add)
ggData[]
}
scatter_test_f(FV,msd, target_test_dt, ref_test_dt)
When only one optional argument is specified I get errors:
First error message gives me: Error in setnames(target_compress, c("V1", "V2"), c(x, y)) : Items of 'old' not found in column names: V1,V2
If I comment out the setnames then I will get the following message: Error in .(ref[[x]], ref[[y]]) : could not find function "."
Oddly enough (to me), when I have both optional argument specified, there are no errors. Anyone know why?
Aucun commentaire:
Enregistrer un commentaire