【问题标题】:how to mutate new variables with different conditions in r如何在r中改变具有不同条件的新变量
【发布时间】:2021-12-30 03:52:23
【问题描述】:

假设我有一个df

df = data.frame(status = c(1, 0, 0, 0, 1, 0, 0, 0),
                stratum = c(1,1,1,1, 2,2,2,2),
                death = 1:8)

> df
  status stratum death
1      1       1     1
2      0       1     2
3      0       1     3
4      0       1     4
5      1       2     5
6      0       2     6
7      0       2     7
8      0       2     8

我想改变一个名为weights 的新变量。并应满足以下条件:

  1. weights 应该在 stratum 组中发生变异。
  2. status1 时,weights 值应返回death 值。

我期望的应该是这样的:

df_wanted =  data.frame(status = c(1, 0, 0, 0, 1, 0, 0, 0),
                        stratum = c(1,1,1,1, 2,2,2,2),
                        death = 1:8,
                        weights = c(1,1,1,1, 5,5,5,5))

> df_wanted
  status stratum death weights
1      1       1     1       1
2      0       1     2       1
3      0       1     3       1
4      0       1     4       1
5      1       2     5       5
6      0       2     6       5
7      0       2     7       5
8      0       2     8       5

我不知道怎么写代码。

任何帮助将不胜感激!

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    您可能会得到death 值,其中status = 1

    library(dplyr)
    
    df %>%
      group_by(stratum) %>%
      mutate(weights = death[status == 1]) %>%
      ungroup
    

    上述方法有效,因为在status = 1 所在的每个组中恰好有 1 个值。如果在 status = 1 的组中有 0 个或多于 1 个值,则更好的选择是使用 match,它将为 0 值返回 NA,并为超过 1 个值返回第一个 death 值。

    df %>%
      group_by(stratum) %>%
      mutate(weights = death[match(1, status)]) %>%
      ungroup
    
    #  status stratum death weights
    #   <dbl>   <dbl> <int>   <int>
    #1      1       1     1       1
    #2      0       1     2       1
    #3      0       1     3       1
    #4      0       1     4       1
    #5      1       2     5       5
    #6      0       2     6       5
    #7      0       2     7       5
    #8      0       2     8       5
    

    【讨论】:

    • 这里我经常使用的另一个选项是 if_else。所以变异调用将是mutate(weights = if_else(status == 1, death, status))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 2020-12-21
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多