r - tidyr 相当于 reshape2::melt() 用于深度嵌套的向量列表

标签 r tidyr reshape2

使用 reshape2,可以轻松地将深度嵌套的向量列表转换为包含每个值的原始列表位置信息的长 data.frame。

# generate nested list of depth 3 with 2 branches at each level
n_l <- purrr::array_tree(
  array(1:2^3, rep_len(2, 3))
)

m_n_l <- reshape2::melt(n_l)

# this provides a df of values where original list position is labelled using 
# [n_dimensions] columns each with [n_branches] values. yay! that's what I want
m_n_l

#    value L3 L2 L1
# 1      1  1  1  1
# 2      5  2  1  1
# 3      3  1  2  1
# 4      7  2  2  1
# 5      2  1  1  2
#        ...

# [reshape2::melt() also handles the case where leaf node vectors have 
# arbitrary number of elements]
reshape2::melt(rapply(n_l, function(x) x * 1:sample(1:3, 1)))

reshape2 现已停用,鼓励其用户使用 tidyr。但是,我找不到 tidyr 方法来复制 reshape2::melt() 的上述功能。 pivot_longer()hoist()unnest() 似乎是替换 melt() 的函数,但是它们似乎专门针对 data.frames 或 data.frames 列表的特殊情况。

tidyr 可以这样做吗?

最佳答案

使用 rrapply 的一个选项可能是:

Reduce(rbind, rrapply(n_l, f = function(x, .xpos) c(.xpos, x), how = "flatten"))

     [,1] [,2] [,3] [,4]
init    1    1    1    1
        1    1    2    5
        1    2    1    3
        1    2    2    7
        2    1    1    2
        2    1    2    6
        2    2    1    4
        2    2    2    8

但是如果您正在寻找一个特定的 tidyverse 选项,那么一个不是很紧凑的选项可能是:

enframe(n_l) %>%
 mutate(value = map(value, ~ enframe(., name = "name2"))) %>%
 unnest(value) %>%
 mutate(value = map(value, ~ enframe(., name = "name3"))) %>%
 unnest(value) %>%
 mutate(value = unlist(value))

   name name2 name3 value
  <int> <int> <int> <int>
1     1     1     1     1
2     1     1     2     5
3     1     2     1     3
4     1     2     2     7
5     2     1     1     2
6     2     1     2     6
7     2     2     1     4
8     2     2     2     8

关于r - tidyr 相当于 reshape2::melt() 用于深度嵌套的向量列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63687606/

相关文章:

r - 如何使用 tidyr Complete 用零完成列?

r - 如何在 R 中整理这个凌乱的数据集

r - anscombe 数据的不那么笨重的 reshape

r - 使用字典/列表来获取键列表

r - geom_function 与 ggplot 中用户编写的函数

当 r 中没有变量值时 reshape

r - 我怎样才能在除一列之外的所有列上收集_?

r - tidyr::spread 和 dplyr::summarise 中的隐式排序

r - 使用基于最大差异的值查找对数差异

r - dcast fun.aggregate 参数