Related to: Reshaping data.frame from wide to long format.
I was wondering which is the best method to reshape data from wide to long format.
Aside from personal style taste, or readability of the code. Which is better in term of performance?
Is there another possible reason as to why one way should be preferred?
Example data:
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
wide to long methods and desired output:
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