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. 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. I am trying to avoid simply listing each observation in hist()
like
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. How can I achieve this elegantly?
If we want to extract the last element of 'height', loop over the list
with sapply
, extract ($
) the column 'height', get the tail
value (sapply
- returns a vector
here) and then apply the hist
hist( sapply(list, function(x) tail(x$height, 1)))