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

Asked

Viewed 69 times

2

I need the cnpj variable that is estre the tags <Parameter> be called as a function parameter. But note that it is within a text block that I use to consume a web service. It is possible somehow?

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>'
}

2 answers

4

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

Using the 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 cases of glue here, for he is very powerful.

  • I didn’t know, thank you very much, it seems to be very useful.

  • William, I tried to use, but I think it lacked some detail to work.

  • 1

    You saw the keys around the CNPJ in the text?

  • Yes, I used the keys but it didn’t work. I will review and try again.

3


See ? For this, argument Collapse. 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 is the function 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.

  • Rui, very good! helped me too much. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.