Make to make R understand data as commands

Hello, Guys! Could someone help me with this?
If i have a function...
funcao <- function(x){
Z <- x*3
}

i can do this... and it works
vector <- c(1,2,3)
Resultado <- funcao(vector)

I want to use the information of a tibble as argument to that function, like this...

tibble <-tribble(
~letras, ~numeros,
"a", c(1,2,3),
"b", c(2,3,4)
)
Resultado <- funcao(tibble[1,2])

What about if i have it in a string? Like this..

string <- text = "c(1,2,3)"
Resultado <- funcao(string)

Can somebody help me, please?
Thank you!

One way to do this is to modify the function to work with different kinds of input.

funcao <- function(x){
  if(!is.vector(x))x <- unlist(x)
  x*3
}

tibl <- tibble::tribble(
  ~letras, ~numeros,
  "a", c(1,2,3),
  "b", c(2,3,4)
)

funcao(1:3)
#> [1] 3 6 9
funcao(tibl[1,2])
#> numeros1 numeros2 numeros3 
#>        3        6        9
funcao(tibl[2])
#> numeros1 numeros2 numeros3 numeros4 numeros5 numeros6 
#>        3        6        9        6        9       12

Created on 2021-01-16 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.