Suppose the user sets dim (1, …., n), and then one or more x_i variables values, with i = 1,…, n.
After some more computations I need to automatically return a dim-dimensional vector vec of the form: (0, 0, 0.2, 0, 0, …, 0.3), where in this specific case the user has set:
dim <- 10
x_3 <- 0.2
x_10 <- 0.3
Of course it is immediate to do:
vec <- rep(0, dim)
vec[3] <- x_3
vec[10] <- x_10
However, since I want to automatize as much operations as possible, I ask you how would you link the x_i variables together with the “respective” element of vec, taking into account that a priori it is not known which/how many variables will be set different from 0.
In other languages this could be done using a for-loop with macro variables… the syntax is wrong, but the idea is something like this:
vec <- rep(0, dim)
for (i in 1:dim) {
if (as.integer(exists(x_i))==1) {
vec[i] <- x_i
}
}
what would you suggest? Thanks!
1 Answer