R: apply a function to every element of two variables respectively

前端 未结 3 962
一整个雨季
一整个雨季 2021-01-02 11:51

I have a function with two variables x and y:

fun1 <- function(x,y) {
  z <- x+y
  return(z)
}

The function work fine by itself:

相关标签:
3条回答
  • 2021-01-02 12:25

    Using dplyr for this problem, as you've described it, is weird. You seem to want to work with vectors, not data.frames, and dplyr functions expect data.frames in and return data.frames out, i.e. it's inputs and outputs are idempotent. For working with vectors, you should use outer. But dplyr could be shoehorned into doing this task...

    # define variables
    Lx  <- c(1:56)
    Ly <- c(1:121)
    dx <- as.data.frame(Lx)
    dy <- as.data.frame(Ly)
    
    require(dplyr)
    require(magrittr)  # for the %<>% operator
    
    # the dplyr solution
    (dx %<>% mutate(dummy_col = 1)) %>% 
         full_join(
             (dy %<>% mutate(dummy_col = 1)), by='dummy_col') %>% 
         select(-dummy_col) %>% 
         transmute(result = Lx + Ly)
    
    0 讨论(0)
  • 2021-01-02 12:33

    If you want to use mapply() you have to provide it with n lists of arguments that have same size, and that will be passed to the function n by n, as in:

    mapply(fun1,c(1,2,3), c(4, 5, 6))
    [1] 5 7 9
    

    or one argument can be a scalar as in:

    mapply(fun1,c(1,2,3), 4)
    [1] 5 6 7
    

    Since you're trying to use all combinations of Lx and Ly, you can iterate one list, then iterate the other, like:

    sapply(Lx, function(x) mapply(fun1,x,Ly))
    

    or

    sapply(Ly, function(y) mapply(fun1,Lx,y))
    

    which produces same result as rawr proposition

    outer(Lx, Ly, fun1)
    

    where outer() is much quicker

    0 讨论(0)
  • 2021-01-02 12:41

    Well you're using vectors of different length but maybe this will help if I understand correctly. I just made a dumby function with variable i

    fun1 <- function(x,y) {
      z <- x+y
      return(z)
    }
    
    
    fun1(15,20)
    
    
    Lx  <- c(1:56)
    Ly <- c(1:121)
    
    
    fun1I <- function(x,y,i)
    {
    
    
      fun1(x[i],y[i])
    
    
    }
    
    
    fun1IR <- function(x,y)
    {
    
    
      function(i)fun1I(x=x,y=y,i=i) #return dumby function
    
    }
    
    
    
    testfun <- fun1IR(Lx,Ly) # creates function with data Lx and Ly in variable i
    
    mapply(testfun, 1:min(length(Lx),length(Ly)))
    
    0 讨论(0)
提交回复
热议问题