Search code examples
rapplymapply

how to map a dataframe and vectors into function parameters with *pply functions


The problem I met is specific operation for *pply(like apply or mapply, etc, I'm not sure).

The dataframe is dlt:

        dlt.1    dlt.2    dlt.3    dlt.4    dlt.5  
  1  3.244198 6.482869 9.711874 12.92918 16.13489
  6  3.196401 6.391871 9.585553 12.77681 15.96547
 19  3.182911 6.365424 9.547196 12.72799 15.90795
 24  3.164079 6.328089 9.491971 12.65577 15.81984

and the vector is freq:

 1 2 3 4 5

Now I intend to map the dt and freqn to a function foo:

foo <- function( dlti, freqi){ dlti * freqi }

where I hope the ith column of dlt correspond to the ith element of freq

I tried apply and mapply, but both failed. Would anyone please show me what is correct way?


Solution

  • It is not clear from your question what you actually want because you don't show the desired result. Without that, there is ambiguity in your question.

        dlt <- tribble(
           ~dlt_1,    ~dlt_2,   ~dlt_3,    ~dlt_4,    ~dlt_5  ,
        3.244198, 6.482869, 9.711874, 12.92918, 16.13489,
        3.196401, 6.391871, 9.585553, 12.77681, 15.96547,
       3.182911, 6.365424, 9.547196, 12.72799, 15.90795,
       3.164079, 6.328089, 9.491971, 12.65577, 15.81984 
    )
    freqi <- c(1,2,3,4,5)
    foo <- function(dlti,freqi){dlti * freqi}
    purrr::map2(dlt,freqi,foo)
    
    $dlt_1
    [1] 3.244198 3.196401 3.182911 3.164079
    
    $dlt_2
    [1] 12.96574 12.78374 12.73085 12.65618
    
    $dlt_3
    [1] 29.13562 28.75666 28.64159 28.47591
    
    $dlt_4
    [1] 51.71672 51.10724 50.91196 50.62308
    
    $dlt_5
    [1] 80.67445 79.82735 79.53975 79.09920