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

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

提交回复
热议问题