Im new in this page. I have been working with this code with no success.
I have a list of parameters.
price<-seq(10,100,length=10)
alfa<-seq(2,3,length=4)
beta<-seq(0.1,0.2,length=4)
the list is:
[[1]]
[1] 10 20 30 40 50 60 70 80 90 100
[[2]]
[1] 2.000000 2.333333 2.666667 3.000000
[[3]]
[1] 0.1000000 0.1333333 0.1666667 0.2000000
and what I want to to is to create a function that, for each price, do the following. I tried with lapply function with no results.
price*beta[1]+alfa[1]
price*beta[2]+alfa[2]
price*beta[3]+alfa[3]
price*beta[4]+alfa[4]
Thanks!
You can usually write the function outside of the lapply() function like this:
price<-seq(10,100,length=10)
alfa<-seq(2,3,length=4)
beta<-seq(0.1,0.2,length=4)
f <- function(price) c(price*beta[1]+alfa[1], price*beta[2]+alfa[2], price*beta[3]+alfa[3], price*beta[4]+alfa[4])
lapply(price, f)
Does this work?
Please provide your lapply code ..
here one more way can possible.. code is
pr <- function(){
new_val <- 0
new_val <- price*alfa+beta
return(new_val)
}
if you want you can use this.
A more natural function for this is Mapply
which takes in vector arguments and applies a function to elements by position.
mapply(function(x, y, price) (price * y) + x, alfa, beta,
MoreArgs=list("price"=price), SIMPLIFY=FALSE)
[[1]]
[1] 3 4 5 6 7 8 9 10 11 12
[[2]]
[1] 3.666667 5.000000 6.333333 7.666667 9.000000 10.333333 11.666667 13.000000 14.333333 15.666667
[[3]]
[1] 4.333333 6.000000 7.666667 9.333333 11.000000 12.666667 14.333333 16.000000 17.666667 19.333333
[[4]]
[1] 5 7 9 11 13 15 17 19 21 23
Here, the MoreArgs argument is used to feed the generic function price as a vector rather than element by element. You could also use the wrapper for mapply
, Map
which always returns a list. This negates the need for the SIMPLIFY
argument:
Map(function(x, y, price) (price * y) + x, alfa, beta, MoreArgs=list(price=price))
[[1]]
[1] 3 4 5 6 7 8 9 10 11 12
[[2]]
[1] 3.666667 5.000000 6.333333 7.666667 9.000000 10.333333 11.666667 13.000000 14.333333 15.666667
[[3]]
[1] 4.333333 6.000000 7.666667 9.333333 11.000000 12.666667 14.333333 16.000000 17.666667 19.333333
[[4]]
[1] 5 7 9 11 13 15 17 19 21 23
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.