【问题标题】:Convert R function from dplyr to data.table将 R 函数从 dplyr 转换为 data.table
【发布时间】:2020-02-06 19:56:55
【问题描述】:

我写了下面的函数,但我需要转换它,所以它不使用 dplyr 库(因为它在大型数据集下很慢)

library(data.table)
library(dplyr)

how_much = 2000
A <- sample(how_much, replace = TRUE, x = 1:5)
B <- sample(how_much, replace = TRUE, x = 1:5)
C <- sample(how_much, replace = TRUE, x = 1:5)
D <- sample(how_much, replace = TRUE, x = 1:5)

VennData = data.table(A, B, C, D)
VennData

Venn_Counts <- function(dataset, unique_number, operator) {
  message("Operator arrgument are: `==` or`<` or `<=` or `>` or `>=`")
  if(inrange(unique_number, 1, 5) ){
    dataset %>% mutate_all( ~ operator(.x, unique_number)) %>%
      group_by_all() %>%
      count()
  }
  else {
    print("Unique number must be in range from 1 to 5")
  }
}



Venn_Counts(VennData, 4, `==`)

【问题讨论】:

    标签: r function dplyr data.table


    【解决方案1】:
    Venn_Counts <- function(dataset, unique_number, operator) {
      message("Operator arrgument are: `==` or`<` or `<=` or `>` or `>=`")
      if (inrange(unique_number, 1, 5)) {
        dataset[, lapply(.SD, operator, 4)][, .N, keyby = names(VennData)]
      }
      else {
        print("Unique number must be in range from 1 to 5")
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多