How to create function where I need to pass the parameter inside a block of text in the R

2

I need the variable cnpj that is the <Parameter> tags to be called as a parameter of a function. But note that it is inside a block of text that I use to consume a web service. Is it possible in any way?

recebeParam <- function(cnpj) {
     Metodo <- '<?xml version="1.0" encoding="utf-8" ?>
         <ResponseFormat>xml</ResponseFormat>
             <Command>
                 <Name>LinxSeguroVendedores</Name>
                     <Parameters>
                         <Parameter id="cnpjEmp">cnpj</Parameter>
                     </Parameters>
                 </Command>'
}
    
asked by anonymous 25.07.2017 / 22:09

2 answers

3

See? paste, collapse argument. Within the function this should solve the problem.

Metodo <- paste('<?xml version="1.0" encoding="utf-8" ?>
         <ResponseFormat>xml</ResponseFormat>
             <Command>
                 <Name>LinxSeguroVendedores</Name>
                     <Parameters>
                         <Parameter id="cnpjEmp">', cnpj, '</Parameter>
                     </Parameters>
                 </Command>', collapse = "")

Note, however, that as the function is, it does not return any value. For this it should be

recebeParam <- function(cnpj) {
    Metodo <- ...etc...
              ...etc...
    Metodo
}

In R , the last statement of a function is the value it returns.

    
26.07.2017 / 00:06
4

The solution of Rui is correct, but when analyzing the way programming is done using strings (interpolation, etc ...) in mature packages in the R language, the package that seems to me most used is glue (at least in tidyverse packages). It has very impressive features given the status of base-r in terms of string manipulations.

Using glue the solution to your problem would be:

library(glue)

recebeParam <- function(cnpj) {
    Metodo <- glue::glue(
        '<?xml version="1.0" encoding="utf-8" ?>
        <ResponseFormat>xml</ResponseFormat>
        <Command>
        <Name>LinxSeguroVendedores</Name>
        <Parameters>
        <Parameter id="cnpjEmp">{cnpj}</Parameter>
        </Parameters>
        </Command>'
    )

    Metodo
}

I suggest taking a look at the usual glue here , because it is very powerful.

    
27.07.2017 / 20:47