【问题标题】:Can't draw histogram using dplyr data manipulation: 'x' must be numeric无法使用 dplyr 数据操作绘制直方图:“x”必须是数字
【发布时间】:2018-05-07 20:02:06
【问题描述】:

我是使用 R 进行数据操作的新手,特别是 dplyr,我正在尝试编写一行代码来生成直方图,它给了我一个错误,即“x”必须是数字,但我可以告诉“x” ' 是数字。

我尝试运行的代码版本如下,对应的错误如下:

mydata %>% filter(Type==1) %>% select(Amount) %>% hist()
Error in hist.default(.) : 'x' must be numeric

如果我将其更改为如下所示的箱线图,则效果非常好:

mydata %>% filter(Type==1) %>% select(Amount) %>% boxplot()

如果我只是跑步:

mydata %>% filter(Type==1) %>% select(Amount)

我得到以下结果,将值显示为 dbl:

# A tibble: 898 x 1
Amount
  <dbl>
 1 -1304.  
 2  -741.  
 3   -38.0 
 4    -1.13
 5     0.  
 6     0.  
 7     0.  
 8     0.  
 9     0.  
10     0.  
# ... with 888 more rows**strong text**

另外,如果我运行以下代码,我会得到我正在寻找的直方图,但我不确定为什么我的原始代码行不起作用。

tmp <- mydata %>% filter(Type==1) %>% select(Amount)
hist(tmp$Amount)

我确信这很简单,但我认为使用 select(Amount) 语句会将该值传递给 hist() 函数,但这似乎没有发生。对我来说奇怪的部分是我可以将其更改为箱线图并且效果很好。对我的原始代码有什么问题有任何想法吗?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    ?hist?boxplot 开始,hist 接受数字向量作为数据,而boxplot 可以接受数字向量或列表。

    要从管道返回数值向量,可以使用pull 将列提取为向量,然后可以将其传递给hist 进行绘图:

    mydata %>% filter(Type==1) %>% pull(Amount) %>% hist()
    

    【讨论】:

    • 嗯,这很容易,我什至没有想到它是作为列表而不是向量传递的(仍然习惯于这些数据类型)。感谢您的帮助!
    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2018-06-24
    相关资源
    最近更新 更多