0

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))
6
  • 2
    Well you don't need to assign them to local variables. p$d0 + p$d11*p$k11 + p$d12*p$k12 could be the entire body of your function. Commented Dec 20, 2017 at 14:59
  • 1
    @Dason please suggest this as an answer before something more complicated (rather than simpler) gets accepted... Commented Dec 20, 2017 at 15:11
  • 1
    equation <- function(p) return(with(p, d0 + d11*k11 + d12*k12)) Commented Dec 20, 2017 at 15:27
  • @Spacedman I didn't write it as an answer because I didn't think the question was entirely appropriate. Seems more like a code review type thing. But I guess I'll put it as an answer since I do think it's probably the best approach for this particular problem and the other answers I'm not really a fan of. Commented Dec 20, 2017 at 16:08
  • You should post your solution as an answer rather than editing it into your question. Commented Feb 14, 2018 at 13:07

4 Answers 4

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.