【问题标题】:Assign value of row based on group of another column R [duplicate]基于另一列R的组分配行的值[重复]
【发布时间】:2021-12-21 23:12:42
【问题描述】:

假设我们有以下数据:

user <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
score <- c(3, 3, 3, NA, 0, 0, 0, NA, NA, NA, NA, NA)
type <- c('new', 'recent', 'recent', 'old', 'recent', 'new', 'new', 'old', 'new', 'new', 'new', 'recent')
df <- data.frame(user, score, type)

df 如下所示:

   user score   type
1     1     3    new
2     1     3 recent
3     1     3 recent
4     1    NA    old
5     2     0 recent
6     2     0    new
7     2     0    new
8     2    NA    old
9     3    NA    new
10    3    NA    new
11    3    NA    new
12    3    NA recent

当type == old 且得分不等于NA(因此不包括用户 3)时,如何完成每个用户类别(1、2 和 3)的案例?

我想要一个像这样的df:

   user score   type
1     1     3    new
2     1     3 recent
3     1     3 recent
4     1     3    old
5     2     0 recent
6     2     0    new
7     2     0    new
8     2     0    old
9     3    NA    new
10    3    NA    new
11    3    NA    new
12    3    NA recent

【问题讨论】:

    标签: r group-by multiple-columns


    【解决方案1】:

    我自己找到的!

    df %>%
      group_by(user) %>%
      fill(score) %>%
      fill(score, .direction = "down")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-23
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多