【问题标题】:Convert melt operation from tidyverse to data.table将熔化操作从 tidyverse 转换为 data.table
【发布时间】:2020-11-16 12:56:29
【问题描述】:

我正在处理一张非常宽的表格,我需要将其转换为更长的格式。通常对于此类任务,我使用tidyverse,但是该表包含大量记录,我想利用data.table 来完成此任务。

您可以在下面找到一个示例数据集,其中包含代码的 tidyverse 版本和使用 data.table 的版本。 我在将感兴趣的列转换为数字时遇到问题。

此代码从 tidyverse 转换为 data.table 的正确方法是什么?

library(data.table)
library(tidyverse)

DT = tibble(
    year_a = 1999:2020,
    year_b = 1999:2020,
    a = as.character(sample(0:1, 22, replace = TRUE)),
    b = as.character(sample(0:1, 22, replace = TRUE)), 
    c = as.character(sample(0:1, 22, replace = TRUE)),
    d = as.character(sample(0:1, 22, replace = TRUE))
)



# tidyverse version
long_DT <- DT %>%
    filter(year_a >= 2010 & year_b >= 2010) %>%
    mutate(across(a:d, .fns = as.double)) %>%
    pivot_longer(cols      = a:d,
                 names_to  = "letter",
                 values_to = "value") %>%
    clean_names()

dim(long_DT)
long_DT %>% glimpse()

# data.table
setDT(DT)
# the line after is causing problems. How to integrate it into the melt function directly?
DT[, select(.SD, a:d)] <- apply(DT[,select(.SD, a:d)], 2, function(x) as.numeric(x))
DT_long <- melt(data = DT[
                    year_a >= 2010 & year_b >= 2010],
                id.vars = c("year_a", "year_b"),
                variable.name = "letter",
                value.name = "value"
            )
dim(DT_long)
DT_long %>% glimpse()

【问题讨论】:

    标签: r data.table tidyverse


    【解决方案1】:

    融化后可能转换为数字:

    res <- melt(DT[year_a >= 2010 & year_b >= 2010, ],
                id.vars = c("year_a", "year_b"),
                variable.name = "letter",
                value.name = "value")[, value := as.numeric(value)]
    

    或者如果我们必须在熔化之前转换为数字:

    cols <- colnames(DT)[3:6]
    res <- melt(DT[year_a >= 2010 & year_b >= 2010, 
                   ][, (cols) := lapply(.SD, as.numeric), .SDcols = cols],
                id.vars = c("year_a", "year_b"),
                variable.name = "letter",
                value.name = "value")
    

    【讨论】:

      猜你喜欢
      • 2018-03-29
      • 1970-01-01
      • 2019-11-23
      • 2019-11-30
      • 2020-02-06
      • 2018-01-17
      • 1970-01-01
      • 2020-08-02
      相关资源
      最近更新 更多