簡體   English   中英

如何在 r 中改變具有不同條件的新變量

[英]how to mutate new variables with different conditions in r

說我有一個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

我不知道如何編寫代碼。

任何幫助將不勝感激!

您可能會在status = 1處獲得death值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM