Vicente
Vicente

Reputation: 1

Accessing variables in a function in R

I was wondering if it is possible to simplify the code of the following function (i.e, if the part of the code: d0 = p$d0, d11 = p$d11, d12 = p$d12, k11 = p$k11, k12 = p$k12 can be replaced by some function) as I am just accessing the variables passed to the function trough the list p.

This is the R code of the function:

equation = function(p){

  d0 =  p$d0
  d11 = p$d11
  d12 = p$d12
  k11 = p$k11
  k12 = p$k12

  result = d0 + d11*k11 + d12*k12

  return(result)
}

equation(list(d0=1,d11=2,d12=3,k11=100,k12=1000))

Upvotes: 0

Views: 54

Answers (4)

Vicente
Vicente

Reputation: 1

I found the solution using list2env(p, envir = environment())

equation = function(p){

  list2env(p, envir = environment())

  result = d0 + d11*k11 + d12*k12

  return(result)
}

equation(list(d0=1,d11=2,d12=3,k11=100,k12=1000))

Upvotes: 0

Dason
Dason

Reputation: 62003

There is no need for anything fancy. You don't have enough that typing the p$ in front of each is overly burdensome and you don't need to assign anything locally. return isn't required so we can actually write your function with a single line body as:

equation <- function(p){
    p$d0 + p$d11*p$k11 + p$d12*p$k12
}

Upvotes: 3

Oriol Mirosa
Oriol Mirosa

Reputation: 2826

Another option is to use the zeallot package, which has the unpacking assignment %<-%:

library(zeallot)

equation = function(p){
  c(d0, d11, d12, k11, k12) %<-% p

  result = d0 + d11*k11 + d12*k12

  return(result)
}

equation(list(d0=1,d11=2,d12=3,k11=100,k12=1000))
## 3201

Upvotes: 0

Colin FAY
Colin FAY

Reputation: 5109

You can simply pass your elements as function arguments :

equation <- function(d0, d11, d12, k11, k12){
  d0 + d11*k11 + d12*k12
}

equation( d0=1, d11=2, d12=3, k11=100, k12=1000)
[1] 3201

Colin

Upvotes: 0

Related Questions