我在列表中有以下元素,我想将它们折叠到一个数据框中,其中只保留列表中相同的列。
我尝试了以下操作,但是并不能完全满足我的需求。因为它只是NA,所以不在其他元素中的列。如果能够选择要折叠的列,我会更好。
n.obs <- sapply(lst, length)
seq.max <- seq_len(max(n.obs))
mat <- t(sapply(lst, "[", i = seq.max))
lst[[1]]
$id
[1] "akromils-production"
$name
[1] "Akro-Mils Production"
$month
[1] 12000
$year
[1] 137000
$units
[1] 3000
$clients
[1] 6
$pbox
[1] FALSE
$punits
[1] 0
$cbox
[1] FALSE
$cunits
[1] 0
$sbox
[1] FALSE
$sunits
[1] 0
$eval
[1] FALSE
$public
[1] FALSE
lst[[2]]
$id
[1] "adc-production-2"
$name
[1] "American Diagnostics - Production (2)"
$month
[1] 26000
$year
[1] 312000
$units
[1] 650
$clients
[1] 2
$pbox
[1] TRUE
$punits
[1] 650
$eval
[1] FALSE
$public
[1] FALSE
答案 0 :(得分:0)
如评论中所述,您应该始终提供可复制的示例数据和代码。最好为dput
提供最少的样本数据,这避免了我们不得不手动键入数据,也避免了由于数据类型未知/模棱两可而造成的歧义。您已经有一段时间了,所以您应该知道如何发布good questions。
针对您的问题,一种选择是使用dplyr::bind_rows
和dplyr::bind_cols
,然后仅选择不包含any
NA
的那些列。 / p>
library(tidyverse)
bind_rows(map(lst, bind_cols)) %>% select_if(~!any(is.na(.x)))
## A tibble: 2 x 10
# id name month year units clients pbox punits eval public
# <chr> <chr> <dbl> <dbl> <dbl> <dbl> <lgl> <dbl> <lgl> <lgl>
#1 akromils-… Akro-Mils Pro… 12000 137000 3000 6 FALSE 0 FALSE FALSE
#2 adc-produ… American Diag… 26000 312000 650 2 TRUE 650 FALSE FALSE
lst <- list(
list(
id = "akromils-production",
name = "Akro-Mils Production",
month = 12000,
year = 137000,
units = 3000,
clients = 6,
pbox = FALSE,
punits = 0,
cbox = FALSE,
cunits = 0,
sbox = FALSE,
sunits = 0,
eval = FALSE,
public = FALSE),
list(
id = "adc-production-2",
name = "American Diagnostics - Production (2)",
month = 26000,
year = 312000,
units = 650,
clients = 2,
pbox = TRUE,
punits = 650,
eval = FALSE,
public = FALSE)
)