简体   繁体   English

R中嵌套列表的直方图

[英]Histogram from nested list in R

I have a nested list similar to this我有一个类似于这个的嵌套列表

df <- data.frame(width = c(1:5),height = c(1:5),depth = c(1:5))
list <- list(df,df*2,df*5,df*1.3)

I would like to make a histogram, in either base R or ggplot, of the final height of each list.我想在每个列表的最终高度的基础 R 或 ggplot 中制作直方图。 I have tried我努力了

hist(tail(list[[1:4]]$height,1))

which yields这产生

Error in list[[1:4]] : recursive indexing failed at level 3

as well as

for (i in 1:4){
hist(tail(list[[i]]$height,1))
}

which generates 4 separate histograms of a single observation.它生成单个观察的 4 个单独的直方图。 I am trying to avoid simply listing each observation in hist() like我试图避免简单地在hist()列出每个观察结果,例如

hist(tail(list[[1]]$height,1),tail(list[[2]]$height,1),tail(list[[3]]$height,1))

because my actual data has many more than 4 sub-lists.因为我的实际数据有超过 4 个子列表。 How can I achieve this elegantly?我怎样才能优雅地实现这一目标?

如果我们想提取 'height' 的最后一个元素,请使用sapply list ,提取( $ )列 'height',获取tail值( sapply - 此处返回一个vector ),然后应用hist

hist( sapply(list, function(x) tail(x$height, 1)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM