【发布时间】: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