dplyr: список векторов для фрейма данных с rbind_all vs bind_rows - PullRequest
3 голосов
/ 07 марта 2019

Я хочу преобразовать список именованных списков во фрейм данных, где в некоторых отсутствуют столбцы.Я могу сделать это успешно с устаревшей rbind_all, но не с заменой bind_rows

Пример Список с отсутствующими столбцами (el3 отсутствует b)

ex = list(el1=c(a=1, b=2, c=3), el2=c(a=2, b=3, c=4), el3=c(a=3, c=5))

rbind_all(ex)
# A tibble: 3 x 3
      a     b     c
  <dbl> <dbl> <dbl>
1     1     2     3
2     2     3     4
3     3    NA     5


> bind_rows(ex)
Error in bind_rows_(x, .id) : Argument 3 must be length 3, not 2

Без пропущенных столбцов

ex2 = list(el1=c(a=1, b=2, c=3), el2=c(a=2, b=3, c=4), el3=c(a=3, b=4, c=5))

rbind_all(ex2)
# A tibble: 3 x 3
      a     b     c
  <dbl> <dbl> <dbl>
1     1     2     3
2     2     3     4
3     3     4     5

bind_rows(ex2) # Output is transposed for some reason
# A tibble: 3 x 3
    el1   el2   el3
  <dbl> <dbl> <dbl>
1     1     2     3
2     2     3     4
3     3     4     5

Как реплицировать поведение rbind_all с помощью устаревшей функции?

Ответы [ 2 ]

4 голосов
/ 07 марта 2019

Пожалуйста, прочитайте этот пример в ?bind_rows:

# Note that for historical reasons, lists containg vectors are
# always treated as data frames. Thus their vectors are treated as
# columns rather than rows, and their inner names are ignored:
ll <- list(
  a = c(A = 1, B = 2),
  b = c(A = 3, B = 4)
)
bind_rows(ll)

# You can circumvent that behaviour with explicit splicing:
bind_rows(!!!ll)

Поэтому, в вашем случае, вы можете попробовать:

ex = list(el1=c(a=1, b=2, c=3), el2=c(a=2, b=3, c=4), el3=c(a=3, c=5))
bind_rows(!!!ex)

# # A tibble: 3 x 3
#       a     b     c
#   <dbl> <dbl> <dbl>
# 1     1     2     3
# 2     2     3     4
# 3     3    NA     5

ex2 = list(el1=c(a=1, b=2, c=3), el2=c(a=2, b=3, c=4), el3=c(a=3, b=4, c=5))
bind_rows(!!!ex2)

# # A tibble: 3 x 3
#       a     b     c
#   <dbl> <dbl> <dbl>
# 1     1     2     3
# 2     2     3     4
# 3     3     4     5
0 голосов
/ 07 марта 2019

Вот обходной путь, который использует map_dfr из пакета purrr.

library(dplyr)
library(purrr)

map_dfr(ex, ~as_tibble(t(.)))
# # A tibble: 3 x 3
#       a     b     c
#   <dbl> <dbl> <dbl>
# 1     1     2     3
# 2     2     3     4
# 3     3    NA     5
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...