'R-create and assign multiple variables from an input vector using loops within a function
I need to optimize multiple objective expressions based on a data frame (i.e., coef.opti).
coef.opti = data.frame(Compound = paste("Compound",1:4,sep=""),
Ingredient1 = c(36.6, 20.8, 109.6, 7.6),
Ingredient2 = c(-7.6,-6.3,-82.2,11.2),
Ingredient3 = c(-7.6,3.8,-14,5.2))
The function can be written manually as fun1.
fun1 = function(x) {x1=x[1]
x2=x[2]
x3=x[3]
y = numeric(4)
y[1] = abs((36.6)*x1+(-7.6)*x2+(-7.6)*x3)
y[2] = abs((20.8)*x1+(-6.3)*x2+(3.8)*x3)
y[3] = abs((109.6)*x1+(-82.2)*x2+(-14)*x3)
y[4] = abs((7.6)*x1+(11.2)*x2+(5.2)*x3)
return(y)
}
But this is time consuming and changing the number of variables or expressions needs re-writing the xs and ys. Can the function be written with for loops or something alike?
For instance, for the x vector, I want to replace
x1 = x[1]
x2 = x[2]
x3 = x[3]
with a loops so that a specified number of variables are created and assigned accordingly and automatically within the function.
The following is what I have so far. But I couldn't get it work.Take 3 variables as an example.
(a = paste("x",1:3,"<-","x[",1:3,"]",sep="",collapse=";"))
noquote(a)
The output looks like this.
[1] x1<-x[1];x2<-x[2];x3<-x[3]
But this is a "noquote," not three separate statements assigning elements of a vector to different variables.
> class(noquote(a))
[1] "noquote"
> is.vector(noquote(a))
[1] FALSE
> typeof(noquote(a))
[1] "character"
I also tried the function cat(). But it prints out.
fun1 = function(x) {
cat(paste("x",1:3," <-,"x[",1:3,"]",sep=""),sep="\n")
y = numeric(4)
y[1] = abs((36.6)*x1+(-7.6)*x2+(-7.6)*x3)
y[2] = abs((20.8)*x1+(-6.3)*x2+(3.8)*x3)
y[3] = abs((109.6)*x1+(-82.2)*x2+(-14)*x3)
y[4] = abs((7.6)*x1+(11.2)*x2+(5.2)*x3)
return(y)
}
> cat(paste("x",1:3," <- ","x[",1:3,"]",sep=""),sep="\n")
x1 <- x[1]
x2 <- x[2]
x3 <- x[3]
The cat() produce the expected except that it prints out.
Similarly, I hope to write the 4 expressions (i.e., y) by looping. Any advice is greatly appreciated!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
