Vladislav Ladenkov Vladislav Ladenkov - 1 month ago 8
R Question

Passing arguments to nested functions with ellipses in R language

Following one tutorial(in my native language), I'm trying to write a function

decorate_string
, which will be able to do this:

decorate_string(pattern = "123", "abc") # "123abc321"
decorate_string(pattern = "123", "abc", "def") # "123abc def321"
decorate_string(pattern = "123", c("abc", "def")) # "123abc321" "123def321"
decorate_string(pattern = "123", "abc", "def", sep = "+") # "123abc+def321"
decorate_string(pattern = "!", c("x", "x"), collapse = "_") # "!x_x!"
decorate_string(pattern = ".:", 1:2, 3:4, 5:6, sep = "&") # ".:1&3&5:." ".:2&4&6:." (вектор длины 2)


TO BE SHORT: It collapses strings with a separetor and segregate it with pattern on the left and reversed pattern on the right.

I've done this:

decorate_string <- function(pattern, ...) {
fock <- function(x, pattern, rev_pat){
x <- paste(pattern, x, rev_pat, collapse = "")
return(x)
}
rev_pat <- paste(rev((strsplit(pattern,NULL))[[1]]), collapse = "")
#a <- paste0(..., sep=" ")
a <- sapply(paste(..., sep=" "), fock)
return(a)
}


But it tells me, that argument
sep
corresponds to severel arguments. I guess, it tries to pass the
sep
argument in the nested function too, right? But nested function doesnt ask for this argument! I DO NOT want the
fock
function to recieve my param. I want only
sapply
to recieve this params!! Whats should i do? Thanks

Answer

As @Dason proposed:" I never said anything about the fock function. That isn't where the issue is. The issue is in your line a <- sapply(paste(..., sep=" "), fock). In that paste statement there is a sep being passed in through the dots and then another sep being specified. You either need to remove the sep from the dotlist manually or have it be a different argument that is passed in in which case it will never be in the dotlist to begin with"