Hüsamettin Tayşi
Hüsamettin Tayşi

Reputation: 574

execute different functions considering output in r

Let's say I have 2 different functions to apply. For example, these functions are max and min . After applying bunch of functions I am getting outputs below. I want to assign a function to each output.

Here is my data and its structure.

    data<-structure(list(Apr = structure(list(`a1` = structure(list(
    date = c("04-01-2036", "04-02-2036", "04-03-2036"), value = c(0, 
    3.13, 20.64)), .Names = c("date", "value"), row.names = 92:94, class = "data.frame"), 
    `a2` = structure(list(date = c("04-01-2037", "04-02-2037", 
    "04-03-2037"), value = c(5.32, 82.47, 15.56)), .Names = c("date", 
    "value"), row.names = 457:459, class = "data.frame")), .Names = c("a1", 
      "a2")), Dec = structure(list(`d1` = structure(list(
    date = c("12-01-2039", "12-02-2039", "12-03-2039"), value = c(3, 
    0, 11)), .Names = c("date", "value"), row.names = 1431:1433, class = "data.frame"), 
    `d2` = structure(list(date = c("12-01-2064", "12-02-2064", 
    "12-03-2064"), value = c(0, 5, 0)), .Names = c("date", "value"
    ), row.names = 10563:10565, class = "data.frame")), .Names = c("d1", 
"d2"))), .Names = c("Apr", "Dec"))

I applied these functions:

 drop<-function(y){
 lapply(y, function(x)(x[!(names(x) %in% c("date"))]))
         }

q1<-lapply(data, drop)
q2<-lapply(q1, function(x) unlist(x,recursive = FALSE))
daily_max<-lapply(q2, function(x) lapply(x, max))
dailymax <- data.frame(matrix(unlist(daily_max), nrow=length(daily_max), byrow=TRUE))
row.names(dailymax)<-names(daily_max)
max_value <- apply(dailymax, 1, which.max)

And I'm getting

Apr Dec 
  2   1 

And I am applying any random function to both Apr[2] and Dec[1] like:

Map(function(x, y) sum(x[[y]]), q2, max_value)

So, the function will be executed considering the outputs (to Apr's second element which is a1, Dec's first element which is a2.) As you can see, there are outputs as numbers 1 and 2.

What I want

What I want is assigning specific functions to 1 and 2. If output is 1 then max function; if it is 2, min function will be executed. In conclusion, max function will be applied to Apr[2] and min function will be applied to Dec[1].

I will get this:

    min(q2$Apr$a2.value)
    [1] 5.32
    max(q2$Dec$d2.value)
    [1] 5

How can I achieve this automatically for all my functions?

Upvotes: 1

Views: 47

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You can take help of switch here to apply a function based on number in max_value.

apply_function <- function(x, num) switch(num, `1` = max, `2` = min)(x)
Map(function(x, y) apply_function(x[[y]], y), q2, max_value)

#$Apr
#[1] 5.32

#$Dec
#[1] 11

Map returns a list if you want a vector output use mapply.

Upvotes: 2

Related Questions