說我有一個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. 并且應滿足以下條件:
weights應該在stratum群體中變異。- 當is時,該
weights值應回傳death值。status1
我期望的應該是這樣的:
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
我不知道如何撰寫代碼。
任何幫助將不勝感激!
uj5u.com熱心網友回復:
你可能會得到death值 where status = 1。
library(dplyr)
df %>%
group_by(stratum) %>%
mutate(weights = death[status == 1]) %>%
ungroup
上面的方法是有效的,因為每個組中正好有 1 個值,其中status = 1. 如果組中有 0 個或 1 個以上的值,status = 1那么更好的選擇是使用match它回傳NA0 值并回傳第一個death值以獲得 1 個以上的值。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397785.html
