R data.table apply function to rows using columns as arguments

前端 未结 3 1445
失恋的感觉
失恋的感觉 2020-12-01 05:39

I have the following data.table

x = structure(list(f1 = 1:3, f2 = 3:5), .Names = c(\"f1\", \"f2\"), row.names = c(NA, -3L), class = c(\"data.tab         


        
相关标签:
3条回答
  • 2020-12-01 05:58

    The best way is to write a vectorized function, but if you can't, then perhaps this will do:

    x[, func.text(f1, f2), by = seq_len(nrow(x))]
    
    0 讨论(0)
  • 2020-12-01 06:06

    The most elegant way I've found is with mapply:

    x[, value := mapply(func.text, f1, f2)]
    x
    #    f1 f2    value
    # 1:  1  3 21.08554
    # 2:  2  4 56.59815
    # 3:  3  5 151.4132
    

    Or with the purrr package:

    x[, value := purrr::pmap(.(f1, f2), func.text)]
    
    0 讨论(0)
  • 2020-12-01 06:11

    We can define rows with .I function.

    dt_iris <- data.table(iris)
    dt_iris[, ..I := .I]
    
    ## Let's define some function
    some_fun <- function(dtX) {
        print('hello')
        return(dtX[, Sepal.Length / Sepal.Width])
    }
    
    ## by row
    dt_iris[, some_fun(.SD), by = ..I] # or simply: dt_iris[, some_fun(.SD), by = .I]
    
    ## vectorized calculation
    some_fun(dt_iris) 
    
    0 讨论(0)
提交回复
热议问题