logo
down
shadow

R: write function with optional arguments


R: write function with optional arguments

By : user2185420
Date : November 21 2020, 04:01 AM
will be helpful for those in need I m trying to write a function that build an API request. The difficulty: I want to use optinal arguments inside the function, and build the API request according to the presence of these optional arguments. Example: , You can do:
code :
myfunction <- function(space, start_date, end_date, ..., optionalArgument4 = NULL){

  args <- c(...)

  filters <- paste(unlist(lapply(seq_along(args),
                           function(i) sprintf("SMALL_filter%s:{$sf%s:'%s'}",
                                                              i, i, args[i]))),
                   collapse = ",")

  api_request <- paste0("https://myapi.com/getData?hello",

                        #NEEDED
                        "&space={s:'", space,"'}",
                        "&period={M:{start:'",start_date,"',end:'",end_date,"'}}",

                        #OPTIONAL
                        ifelse(filters=="","",sprintf("&filter={%s}",filters)),

                        ifelse(!is.null(optionalArgument4),
                               paste0("&segment=",optionalArgument4),"")

  )

  return(api_request)    
}
space <- "earth"
start_date <- "2018-10"
end_date <- "2018-11"
optionalArgument1 <- "America"
optionalArgument2 <- "people"
optionalArgument3 <- "size"
optionalArgument4 <- "ocean"

myfunction(space, start_date, end_date, optionalArgument1, optionalArgument4 = optionalArgument4)
# [1] "https://myapi.com/getData?hello&space={s:'earth'}&period={M:{start:'2018-10',end:'2018-11'}}&filter={SMALL_filter1:{$sf1:'America'}}&segment=ocean"


Share : facebook icon twitter icon
How to write a test for a function with optional arguments

How to write a test for a function with optional arguments


By : kukushka_kryaka
Date : March 29 2020, 07:55 AM
this will help You may be able to use the * operator:
code :
@pytest.mark.parametrize('args,expected', [
    ([], expVal0),
    ([key, "city", 0], expVal1),
    ([key, 'contact_no', 2, {}, policy], expVal2)
    ([key, "contact_no", 0], expVal3)
    ([key, "contact_no", 1, {}, policy, ""], expVal4)
    ([key, "contact_no", 0, 888], expVal5)
])
def test_list_get(args, expected):
    assert list_get(*args) == expected
Write a JavaScript function that changes behavior based on optional arguments

Write a JavaScript function that changes behavior based on optional arguments


By : Daoud Fares
Date : March 29 2020, 07:55 AM
this one helps. The way you are doing is it fine, but here's a few tips.
1) In ES6 you could have a default argument in case one is not supplied:
code :
function foo(optionalArg = 'something cool') {
   // have your function go about its business as usual
}
function foo(optionalArg) {
   if (optionalArg === undefined) {
      optionalArg = 'something cool'
   }
   // have your function go about its business as usual
}
function foo(optionalArg) {
    if (optionalArg !== undefined) {
        // do something with the optionalArg
    } else {
        // do something different
    }
}
function foo(optionalArg) {
   if (optionalArg !== undefined) {
     // do something with the optionalArg
   } else {
     // do something different
     // big
     // huge
     // grandiose
     // epic
   }
}
Pythonic way to write REST wrapper function that takes optional arguments

Pythonic way to write REST wrapper function that takes optional arguments


By : user1407205
Date : March 29 2020, 07:55 AM
may help you . Disclaimer: questions like what is the most Pythonic (best/prettiest) way can attract unnecessary discussion (and create a distraction) yielding an inconclusive results. My personal recommendation, over reusing recommendation from a particular part of the community would be above all: be consistent across your code and how you design your interfaces. Think of those who will use them (incl. yourself 12 months down the road). As well as "The Best" solution is usually function of the intended purpose and not necessarily a universal constant (even though there might be more or less recommendable ways). That said.
If I understand correctly, your parameters are of key=value pairs nature (and you will expand them into URL as search_parameters[key]=value). Event though the filter and orientation in your example throw me off... if not true, please, describe a bit more and I can revisit my suggestion. For that a dictionary seems to offer itself as a good choice. To get one, your method could be either:
code :
def search(self, search_kwargs):
    ...
def search(self, **kwargs):
    ...
not ('string' in my_args or 'value' in my_args):
    raise SearchParamsError("Require 'string' or 'value'.")
url_params = '&'.join(('{}={}'.format(k, my_dict[k]) for k in my_dict))
my_dict = {'string': 'foo bar',
           'author_id': 12345,
           'filter': {'orientation': 'horizontal',
                      'other': 'baz'},
           'other': {'more': {'nested': 1,
                              'also': 2},
                     'less': 'flat'}}

def par_dict_format(in_dict, *, _pfx='search_parameters'):
    ret = []
    for key, value in in_dict.items():
        if isinstance(value, dict):
            ret.append(par_dict_format(value, _pfx='{}[{}]'.format(_pfx, key)))
        else:
            ret.append('{}[{}]={}'.format(_pfx, key, value))
    return '&'.join(ret)
my_dict = {'string': 'foo bar',
           'author_id': 12345,
           'filter.orientation': 'horizontal',
           'filter.other': 'baz',
           'other.more.nested': 1,
           'other.more.also': 2,
           'other.more.also': 2,
           'other.less': 'flat'}

def par_dict_format(in_dict):
    ret = []
    for key, value in in_dict.items():
        key_str = ''.join(('[{}]'.format(p) for p in key.split('.')))
        ret.append('{}={}'.format(key_str, value))
    return '&'.join(('search_parameters{}'.format(i) for i in ret))
lapply with optional function argument and optional vector arguments

lapply with optional function argument and optional vector arguments


By : Davaakhuu Erdenekhuu
Date : March 29 2020, 07:55 AM
wish helps you I have a function in R, say , This uses the dots aka the ... argument:
code :
foo2 <- function(...) {
#I just returns the identity
  l <- lapply(..., I)
  a <- l[[1]]
  b <- l[[2]]
  c <- l[[3]]

  for(n in 1:N){
    out[n] <- b%*%b+ a(n)*c
  }
  return(out)
  }


candidates <- list(a=a, b = c(1:3), c=1000)

foo2(candidates)
# or to simplify. Same output as previous.
c(crossprod(1:3)) + sqrt(seq_len(100)) * 1000

  [1]  1014.000  1428.214  1746.051  2014.000  2250.068  2463.490  2659.751  2842.427  3014.000  3176.278  3330.625  3478.102  3619.551  3755.657
 [15]  3886.983  4014.000  4137.106  4256.641  4372.899  4486.136  4596.576  4704.416  4809.832  4912.979  5014.000  5113.020  5210.152  5305.503
 [29]  5399.165  5491.226  5581.764  5670.854  5758.563  5844.952  5930.080  6014.000  6096.763  6178.414  6258.998  6338.555  6417.124  6494.741
 [43]  6571.439  6647.250  6722.204  6796.330  6869.655  6942.203  7014.000  7085.068  7155.428  7225.103  7294.110  7362.469  7430.198  7497.315
 [57]  7563.834  7629.773  7695.146  7759.967  7824.250  7888.008  7951.254  8014.000  8076.258  8138.038  8199.353  8260.211  8320.624  8380.600
 [71]  8440.150  8499.281  8558.004  8616.325  8674.254  8731.798  8788.964  8845.761  8902.194  8958.272  9014.000  9069.385  9124.434  9179.151
 [85]  9233.544  9287.618  9341.379  9394.832  9447.981  9500.833  9553.392  9605.663  9657.651  9709.360  9760.794  9811.959  9862.858  9913.495
 [99]  9963.874 10014.000
How can I pass optional arguments on to another function which has optional arguments

How can I pass optional arguments on to another function which has optional arguments


By : MTKConsult
Date : March 29 2020, 07:55 AM
may help you . Just pass the arguments along the chain. As a very simplistic example:
Related Posts Related Posts :
  • Finding income ratio by student status
  • Sum and Count Changes per Group for each Column in R
  • Writing a Path/Route Plot as a GeoTiff in R
  • Shorter order expression in R
  • Make a function using apply, stringr, stringi, and rbind run faster
  • Using cast() or ddply() to summarise the mean for two continuous variables in one dataframe
  • How to assign ID to multiple rows based on a value in 1 column in 1 row duplicating a value in a DIFFERENT column in a d
  • apply transparent background to divide plot area based on x values using ggplot
  • pivot a data frame and exclude blank cells in r
  • Subsetting Polygons from Spatial Polygons object by slot
  • Error: Don't know how to add e2 to a plot
  • selecting values from a df based on multiple percentages from a different dataframe
  • Why does R paste more decimals than have been rounded, but only sometimes?
  • Emacs ESS indent after %>%
  • Editing data frame after reactive upload in R shiny
  • R: How to add a zero into the middle of a string
  • Write a loop to select all combination of variable values generating positive equation values in R
  • Parameterizing group_by %>% summarise
  • How to display HTML in DT header?
  • R Vectorizing Operation
  • Cystoscape node color
  • geom_tile border missing at corners
  • Geting new data into old data frame in R
  • Eigenvector values for different time periods of same network (igraph in R)
  • Write a function with default column name inputs in dplyr::mutate()
  • Why isn't string splitting after last open parenthesis?
  • blogdown - how do I specify which page a post will appear on
  • Can I span groups of categories with horizontal lines in ggplot2
  • RODBC gives proper row count but yields empty query
  • Merging two incomplete factors
  • reshaping data with time represented as spells
  • R ggplot: How to create a scatter plot with marginal box plots
  • Rcpp use outer with pmax
  • Symbolic matrix mutiplication error (Ryacas)
  • Creating columns based on total number of columns in a data frame R
  • How do I address R raster mosaic error: 'data' must be of a vector type, was 'NULL'?
  • ggplot2() plotting one variable against itself by factor?
  • Random sets with three random numbers in it (sampling random points in a cube)
  • Function to find varying strings
  • How do I post some introductory paragraphs on the main page of my blogdown site?
  • Correlations between numerous variables grouped in dplyr
  • Animating 3d object in R Markdown html with play3d
  • Suppress multiple package/library loading messages
  • R CMD REMOVE has no effect
  • repeated observations average per month
  • Count values per year and based on other column
  • aggregating elements to create groups of minimal size
  • efficient subsetting of data.table with greater-than, less-than using indices
  • Prefix/suffix column content with column names
  • ggplot and ggsignif error on grouping variable
  • R - How to use sum and group_by inside apply?
  • For Each Loop to convert into numeric values
  • How to summarise taking a random value from a categorical column?
  • Predictions in SageMaker ::: Writing Function To Split Big Data-frame Into Batches For Predictions
  • ggplot: How to keep marker colours in legend but hide text colours?
  • Removing character elements from a vector
  • Cumulative sum based on factor on R
  • expand colnames to match the last known one
  • `testthat::expect_silent()` does not seem to notice ggplot2 errors
  • Parse Factor in R
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org