【发布时间】:2020-04-08 03:36:48
【问题描述】:
一个简单的问题,但我已经搜索了解决方案,但到目前为止无济于事。
假设我有一个列表对象,我想提取特定的列表元素并将它们并排输出为数据框列。如何以简单的方式通过 tidyverse/管道实现这一点?尝试在下面解决它。
数据
some_data <-
structure(list(x = c(23.7, 23.41, 23.87, 24.18, 24.15, 24.31,
23.14, 23.72, 24.12, 23.47, 23.59, 23.29, 23.24, 23.5, 23.56,
23.16, 23.62, 23.67, 23.84, 23.69, 23.7, 23.68, 24.2, 23.77,
23.74, 23.64, 24.39, 24.05, 24.51, 23.6, 24.29, 23.31, 23.96,
24.07, 24.37, 23.77, 23.64, 24, 23.68, 24.02, 23.36, 23.54, 23.34,
23.69, 23.79, 23.8, 23.7, 24.45, 23.27, 23.57, 23.02, 24.23,
23.41, 23.6, 24.02, 23.94, 24.06, 23.97, 23.38, 23.46, 24, 23.89,
23.51, 23.72, 23.83, 23.96, 23.84, 23.52, 24.36, 23.94, 23.82,
24.04, 24.05, 23.6, 23.52, 24.13, 23.43, 23.33, 24.01, 23.99,
24.46, 24.23, 24.19, 23.83, 23.8, 23.93, 23.79, 23.48, 23.26,
24.04, 23.93, 23.98, 23.86, 23.49, 24.17, 23.7, 23.54, 23.55,
23.67, 23.66)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -100L), spec = structure(list(cols = list(
x = structure(list(), class = c("collector_double", "collector"
))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))
我想要这个数据的`hist()`函数的值输出
library(tidyverse)
some_data$x %>%
as.numeric() %>%
hist(breaks = seq(from = 23, to = 24.6, by = 0.2),
plot = FALSE)
## $breaks
## [1] 23.0 23.2 23.4 23.6 23.8 24.0 24.2 24.4 24.6
## $counts
## [1] 3 9 20 23 19 16 7 3
## $density
## [1] 0.15 0.45 1.00 1.15 0.95 0.80 0.35 0.15
## $mids
## [1] 23.1 23.3 23.5 23.7 23.9 24.1 24.3 24.5
## $xname
## [1] "."
## $equidist
## [1] TRUE
## attr(,"class")
## [1] "histogram"
假设我希望将 `$breaks` 和 `$counts` 并排作为一个数据框
我将补充原来的管道,以便:
some_data$x %>%
as.numeric() %>%
hist(breaks = seq(from = 23, to = 24.6, by = 0.2),
plot = FALSE) %>%
##
map_df(~.[1:30]) %>%
select(bins = breaks,
frequency = counts)
##
## # A tibble: 30 x 2
## bins frequency
## <dbl> <int>
## 1 23 3
## 2 23.2 9
## 3 23.4 20
## 4 23.6 23
## 5 23.8 19
## 6 24 16
## 7 24.2 7
## 8 24.4 3
## 9 24.6 NA
## 10 NA NA
## # ... with 20 more rows
所以是的,它确实有效,但是在map_df() 中,我必须输入一个相对较大的“神奇”数字(我随意输入 30)以确保包含所有数据。有没有更简单的方法来获取 $breaks 和 $counts 作为数据框?或许只需一步而不是将map_df() 和select() 结合起来?
评论
虽然这个特定问题展示了histogram 类的情况,但我的一般问题不是关于直方图,而是关于列表对象的原则。 hist(plot = FALSE) 的输出的好处在于它生成了一个包含不等长元素的对象,这说明了一个需要灵活解决方案来解决元素长度变化的问题。
解决方案
基于下面 Rémi Coulaud 的(选择的)解决方案,解决列表元素长度不等的情况的方法是使它们相等,锚定到最长的元素。然后,这不再是问题了。工作管道如下:
library(tidyverse)
some_data$x %>%
as.numeric() %>%
hist(breaks = seq(from = 23, to = 24.6, by = 0.2),
plot = FALSE) %>%
lapply(., `length<-`, max(lengths(.))) %>% ## make all elements as the length of the longest one
map_df(~.) %>%
select(bins = breaks,
frequency = counts)
谢谢!
【问题讨论】: