【问题标题】:plotting the individual histograms after lapply in R在 R 中绘制 lapply 后的各个直方图
【发布时间】:2016-09-12 07:28:07
【问题描述】:

在数据表上使用 lapply 后,我在绘制 个人 直方图时遇到问题。该指令绘制了所有直方图,但我需要单独访问它们。所有直方图对象都在列表中可用,但是当我访问(例如)最后一个直方图对象并尝试绘制它时,会出现错误。代码如下所示。

我使用 mt cars 数据集并从中形成一个表格。

library(data.table)
mtcars$carname <- rownames(mtcars)
mtcars_dt <- data.table(mtcars)
histograms<- mtcars_dt[, lapply(.SD[, 1:10, with=F], hist), by=cyl]
# The above will plot all 30 data frames ie 10 for each value of cyl (3 of) 
# I now want to plot a single histogram, lets say the 10th one
b=histograms[[10]] # this is a histogram object
plot(b) # try to plot the object 
#
# Result is the error shown below:

# Error in if (freq && !equidist) warning("the AREAS in the plot are wrong -      
#- rather use 'freq = FALSE'") : 
#missing value where TRUE/FALSE needed
# In addition: Warning messages:
# 1: In min(x, na.rm = na.rm) :
# no non-missing arguments to min; returning Inf
# 2: In max(x, na.rm = na.rm) :
##no non-missing arguments to max; returning -Inf
#3: In mean.default(h) : argument is not numeric or logical: returning NA

我以前绘制过 histogram 对象,但我注意到当我对这个对象执行 str 时,列表中的元素比简单的 histogram 多得多。最后一个元素是一个 attr 元素,其旁边带有单词 histogram。我不确定是否需要访问该元素或锄头才能访问它。

感谢任何帮助

谢谢 G

【问题讨论】:

    标签: r plot datatables histogram lapply


    【解决方案1】:

    我不是data.table 专家。但我会使用ggplot2 来做这样的事情:

    首先创建一个函数,为每个cyl 组绘制三个直方图

    foo <- function(x){
     require(ggplot2)
     ggplot(mtcars, aes(x = x)) + geom_histogram() + facet_grid(. ~ cyl)
    }
    

    在列上应用函数,将绘图保存在列表中

    histograms <- lapply(mtcars, foo)
    

    现在您可以通过

    访问各个图
    histograms[3]
    # or
    histograms$disp
    

    【讨论】:

    • 谢谢,我会用表格试试你的解决方案,它应该像适用于数据框一样工作。否则我会转换。
    猜你喜欢
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2015-07-12
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多