Reputation: 51
I have 5 parameters with some values in a named vector.
Vector 1 =("param1" = 10,"param2"=20,param3=30,param4=20,param5=60)
Param1 has some multiplier value which is 3(param1 *3) param2 has some multiplier value which is 2 (Param2 *2)
For param3,param4,param5 we have to take mean if any those three parameters presen and its multiplier values is one (average of three params * 1)
For example if the values are present in Vector 1: Note : average of three params is param3,param4,param5
result = param1 * 3 + param2 *2 + average of three params * 1 / 3 + 2 + 1
If any parameter in the vector1 is not present the code should produce output for
example: if param1 not present in Vector 1
result = param2 * 2 + average of three params * 1 / 2 + 1
the expression should be dynamic based on parameters present in Vector 1
Example
Input = c("param1" = 10,"param2" = 20, "param3" = 40, "param4"= 60, "param5 = 20")
If all the parameters are present in the Input vec the expression should be:
expression = 10*3 + 20*2 + (40+60+20/3) * 1 / 3+2+1
If param2 is not present in the Input vec the expression should be:
expression = 10*3 + (40+60+20/3) * 1 / 3 + 1
If param4 is not present the expression should be :
expression = 10*3 + 20 * 2 + (40+20/2) * 1 / 3 + 2 + 1
If param3, param4, param5 not present
expression = 10 * 3 + 20 * 2 / 3 + 2
Upvotes: 0
Views: 73
Reputation: 1450
You can benefit from several facts:
1) When you index a named vector by a name that does not exist, it returns NA
.
2) A mathematical operation involving NA
will also return NA
.
3) The sum()
and mean()
functions have an optional parameter na.rm
, that lets you remove NA
values from the computation automatically.
4) A mathematical operation involving a logical condition will treat the logical value (TRUE
or FALSE
) as numerical 1
or 0
.
So your code could be like this:
Vector1 <- c(param1=10, param2=20, param3=30, param4=20, param5=60)
expression <- sum(
Vector1["param1"] * 3,
Vector1["param2"] * 2,
mean(c(Vector1["param3"], Vector1["param4"], Vector1["param5"]), na.rm = TRUE),
na.rm = TRUE
) / sum(
3 * !is.na(Vector1["param1"]),
2 * !is.na(Vector1["param2"]),
1 * !is.nan(mean(c(Vector1["param3"], Vector1["param4"], Vector1["param5"]), na.rm = TRUE))
)
Upvotes: 2
Reputation: 101848
Maybe you can try the code like below
wts <- c(3,2,1)
lst <- list("param1","param2",c("param3","param4","param5"))
u <- unlist(Map(function(v) mean(Input[names(Input)%in% v]), lst))
result <- sum(u*wts,na.rm = TRUE)/sum(wts[!is.na(u)])
Example
> Input
param1 param2 param3 param4 param5
10 20 40 60 20
> result
[1] 18.33333
> Input
param1 param3 param4 param5
10 40 60 20
> result
[1] 17.5
> Input
param1 param2
10 20
> result
[1] 14
> Input
param3 param4 param5
40 60 20
> result
[1] 40
Upvotes: 1