繁体   English   中英

从宽格式到长格式的最佳方法重塑

[英]best method reshaping from wide to long format

与以下内容有关:将data.frame从宽格式重塑为长格式

我想知道哪种方法是将数据从宽格式转换为长格式的最佳方法。

除了个人风格的品味或代码的可读性。 在性能方面哪个更好?

为什么应该首选一种方法还有另一个可能的原因吗?

示例数据:

v <- 1:3
names(v) <- paste0("col_", 1:3)
d <- purrr::map_df(v, function(x) runif(5, 0, 1))
d$id <- 1:5
# # A tibble: 5 x 4
# col_1  col_2 col_3    id
# <dbl>  <dbl> <dbl> <int>
# 1 0.262 0.755  0.132  1
# 2 0.306 0.0344 0.571  2
# 3 0.143 0.628  0.933  3
# 4 0.401 0.709  0.629  4
# 5 0.353 0.691  0.405  5

广泛的方法和所需的输出:

library(dplyr)
# tidyr
d %>% tidyr::gather("key", "value", -id) %>% head()
# reshape2
reshape2::melt(d, id.vars=c("id")) %>% head()
# DT
data.table::melt(dt, id.vars=c("id")) %>% head()

# output:
#   id variable     value
# 1  1    col_1 0.2618043
# 2  2    col_1 0.3059923
# 3  3    col_1 0.1433476
# 4  4    col_1 0.4007300
# 5  5    col_1 0.3531845
# 6  1    col_2 0.7550252

在性能方面,似乎在较大的示例中, reshape2::melt是最快的,但老实说,我们所说的是毫秒。

较大数字的示例:

# bigger numbers example
v <- 1:100
names(v) <- paste0("col_", 1:100)
d <- purrr::map_df(v, function(x) runif(100000, 0, 1))
d$id <- 1:100000

dt <- as.data.table(d) # for dt  

微基准测试:

microbenchmark::microbenchmark(
  gather = {gather(d, "key", "value", -id)},
  melt = {melt(d, id.vars=c("id"))},
  dt = {melt(dt, id.vars=c("id"))},
  times = 100
)
# Unit: milliseconds
# expr        min       lq     mean   median       uq      max neval
# gather 50.75434 51.61489 64.90385 61.06314 68.10268 201.7082   100
# melt   12.08457 12.58755 19.77046 13.13005 22.29556 162.0733   100
# dt     42.80573 44.50143 50.62359 45.04182 54.15235 187.1778   100

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM