2

我有一个包含多个数据框的列表列表。我想转置数据框并保持列表结构不变。

数据以这种格式设置(来自:John McDonnell):

parent <- list(
  a = list(
    foo = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)),
    bar = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)),
    puppy = data.frame(first = c(1, 2, 3), second = c(4, 5, 6))
  ),
  b = list(
    foo = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)),
    bar = data.frame(first = c(1, 2, 3), second = c(4, 5, 6)),
    puppy = data.frame(first = c(1, 2, 3), second = c(4, 5, 6))
  )
)

这在使用单个数据框列表时有效,但不适用于列表列表:

a_tran <- lapply(a, function(x) {
  t(x)
})

关于如何修改的任何想法?

4

1 回答 1

3

你可以modify_depth使用purrr

library(purrr)
modify_depth(.x = parent, .depth = 2, .f = ~ as.data.frame(t(.)))
#$a
#$a$foo
#       V1 V2 V3
#first   1  2  3
#second  4  5  6

#$a$bar
#       V1 V2 V3
#first   1  2  3
#second  4  5  6

#$a$puppy
#       V1 V2 V3
#first   1  2  3
#second  4  5  6


#$b
# ...

@hrbrmstr 最初在评论中发布的base R选项是

lapply(parent, function(x) lapply(x, function(y) as.data.frame(t(y))))
于 2018-12-01T22:20:05.937 回答