[英]R: Assign value to group based on condition
通過為組分配值,我遇到了問題。 例如我的數據看起來像:
example.frame = data.frame("ID" = c(1,1,1,1,2,2,2,3,3,3,3,4,4), "AL" = c(1,1,2,4,2,3,4,1,5,1,2,3,4))
現在我想生成一個新變量true
,如果任何 AL 包含 1 則將 1 分配給整個組( ID
),這樣生成的 dataframe 看起來像:
example.frame = data.frame("ID" = c(1,1,1,1,2,2,2,3,3,3,3,4,4), "AL" = c(1,1,2,4,1,3,4,1,5,1,2,3,4), "true" = c(1,1,1,1,0,0,0,1,1,1,1,0,0))
如果有人知道如何做到這一點,那就太好了。
library(tidyverse)
example.frame = data.frame("ID" = c(1,1,1,1,2,2,2,3,3,3,3,4,4), "AL" = c(1,1,2,4,2,3,4,1,5,1,2,3,4))
example.frame %>%
group_by(ID) %>%
mutate(true=length(AL[AL==1])) %>% #number of 1s per group
mutate(true=case_when(true>0 ~ 1, #if larger than 0 => 1
TRUE ~ 0))
#> # A tibble: 13 x 3
#> # Groups: ID [4]
#> ID AL true
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 1 2 1
#> 4 1 4 1
#> 5 2 2 0
#> 6 2 3 0
#> 7 2 4 0
#> 8 3 1 1
#> 9 3 5 1
#> 10 3 1 1
#> 11 3 2 1
#> 12 4 3 0
#> 13 4 4 0
由代表 package (v0.3.0) 於 2020 年 12 月 2 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.