首页 > 解决方案 > 用户在 R 中写的平均帖子数

问题描述

我有一个带有文本和 user_type 的数据框。我想获得 user_type 所写帖子的平均数量。

数据:

df$post
[1] "hi my name is"
[2] "hey how are you"
[3] "whats up"

df$user_type

[1] big_user
[2] big_user
[3] small_user

标签: rtextaveragetapply

解决方案


使用dplyr

# counting the posts per user
df %>%
  count(user_type)
#    user_type n
# 1   big_user 2
# 2 small_user 1

# calculating the average length of posts per user
df %>% 
  group_by(user_type) %>%
  summarise(average = sum(str_count(text))/n(), .groups="drop")
#   A tibble: 2 x 2
#   user_type  average
#   <chr>        <dbl>
# 1 big_user        14
# 2 small_user       8

使用base R

table(df$user_type)
#   big_user small_user 
#          2          1 

推荐阅读