【问题标题】:Top rows of count of a specific column in DF in RR中DF中特定列的前几行
【发布时间】:2020-10-15 05:20:50
【问题描述】:

这是我的数据集 - https://www.kaggle.com/dgomonov/new-york-city-airbnb-open-data

我一直在尝试为数据集中最繁忙的 ID 创建直方图。

所以首先我创建计数

hostcount <-plyr::count(nycab2$host_id)

然后我尝试只使用前 1-

hostcounttop <- head(arrange(hostcount, decreasing = TRUE), n = 10)

但我得到了这个错误

Error: Length of ordering vectors don't match data frame size

我的代码有什么问题,因为它是相同的数据框大小?

【问题讨论】:

    标签: r


    【解决方案1】:

    arrange 没有 decreasing = TRUE 参数。您可以在列名上使用desc

    不过,plyr 已停用,大部分功能在dplyr 中可用。你可以这样做:

    library(dplyr)
    hostcounttop  <- nycab2 %>%  count(host_id) %>% slice_max(n, 1)
    #If you have dplyr version < 1.0.0 use `top_n`.
    #hostcounttop <- nycab2 %>%  count(host_id) %>% top_n(1, n)
    

    在基础 R 中,我们可以这样做:

    mat <- stack(table(nycab2$host_id))
    mat <- mat[order(mat$values), ]
    #to get top 10 values use tail
    tail(mat, 10)
    

    【讨论】:

    • 我试过你的公式,但由于某种原因它给了我这个Error in count(., host_id) : object 'host_id' not found,这没有意义,因为DF显然有host_id
    • 是的,我认为您的代码使用的是plyr::count。尝试将它与dplyr::count 一起使用,就像这样nycab2 %&gt;% dplyr::count(host_id)
    • hostcounttop &lt;- nycab2 %&gt;% dplyr::count(host_id) %&gt;% slice_max(n, 1),试过这个,现在我得到这个错误Error: `...` is not empty. We detected these problematic arguments: * `..1` These dots only exist to allow future extensions and should be empty. Did you misspecify an argument?,所以我跑了rlang::last_error,它给了我这个。 &lt;error/rlib_error_dots_nonempty&gt; `...` is not empty. We detected these problematic arguments: * `..1` These dots only exist to allow future extensions and should be empty. Did you misspecify an argument?
    • 适用于 mtcars 对我的示例:mtcars %&gt;% count(cyl) %&gt;% slice_max(n, 1)。以上对你有用吗?也许您需要更新软件包,因为这些帖子中很少有人建议 stackoverflow.com/questions/60021210/…stackoverflow.com/questions/61599249/…
    • 我注意到很多其他人和我有同样的问题。不幸的是,我的情况似乎没有任何效果。有没有其他不使用 dplyr 的方法可以提供帮助?
    【解决方案2】:

    您可以尝试使用order() 代替排列,并使用括号对数据框进行子集?

    例如假设问题不在于您的数据框,请尝试:

    order(hostcount, decreasing = TRUE)[1:10]
    

    您可以更改 1:10 以获得尽可能多的数据。

    【讨论】:

    • 不幸的是,它没有将其转为一个价值,而不是分贝。我试图将前 10 名主机放入直方图中。
    • 您能否发布一小部分数据集供我们使用?我会尝试解决为什么我的解决方案无法在我自己的计算机上运行,​​但我不想为了下载数据集而注册 kaggle,哈哈。
    • 当然。我该怎么做呢?
    • 也许您可以尝试使用数据更新您的原始帖子?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 1970-01-01
    相关资源
    最近更新 更多