【问题标题】:Analog to Pandas Series.value_counts() in R? [duplicate]类似于 R 中的 Pandas Series.value_counts()? [复制]
【发布时间】:2020-06-11 22:56:15
【问题描述】:

Python 中,可以使用Series.value_counts() 获取列表中值的计数:

import pandas as pd

df = pd.DataFrame()
df['x'] = ['a','b','b','c','c','d']
df['y'] = list(range(1,7))

df['x'].value_counts()

c    2
b    2
a    1
d    1
Name: x, dtype: int64

R 中,我必须使用三个单独的命令。

df <- tibble(x=c('a','b','b','c','c','d'), y=1:6)

df %>% group_by(x) %>% summarise(n=n()) %>% arrange(desc(n))

x   n
b   2
c   2
a   1
d   1

在 R 中有更短/更惯用的方法吗?还是我最好写一个自定义函数?

【问题讨论】:

  • dplyr::count(df, x, sort = TRUE)
  • table(df$x)怎么样
  • 谢谢@rpolicastro,这就是我想要的!如果您提交,我可以标记为答案。
  • 很高兴我能帮上忙!我提交了答案。

标签: r pandas dplyr


【解决方案1】:

tidyverse 有 dplyr::count,这是 'group_by' 和 'summarize' 获取计数的快捷方式。

df <- tibble(x=c('a','b','b','c','c','d'), y=1:6)

dplyr::count(df, x, sort = TRUE)

# A tibble: 4 x 2
  x         n
  <chr> <int>
1 b         2
2 c         2
3 a         1
4 d         1

【讨论】:

    猜你喜欢
    • 2019-12-19
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2018-10-23
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多