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

前端 未结 3 994
一整个雨季
一整个雨季 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: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)))
    

提交回复
热议问题