如果(我的變數)滿足多個條件一次或多次,我正在嘗試用nat_locx第一行中的值替換所有值。LOCXidgroup_by()
這是我的資料示例:
id DATE nat_locx LOCX distance loc_age
<fct> <date> <dbl> <dbl> <dbl> <dbl>
6553 2004-06-27 13.5 2 487.90 26
6553 2004-07-14 13.5 13.5 0 43
6553 2004-07-15 13.5 12.5 30 44
6553 2004-07-25 13.5 14.5 44.598 54
6081 2004-07-05 13 14.2 40.249 44
6081 2004-07-20 13 13.8 61.847 49
我嘗試這樣做的方式是這樣的:
df<-df %>%
group_by(id) %>%
mutate(nat_locx=ifelse(loc_age>25 & loc_age<40 & distance>30, first(LOCX), nat_locx))
但是,當我這樣做時,它只會將第一行替換為列中的第一個值,而不是我的變數 ( )LOCX的所有nat_locx值。group_byid
理想情況下,我想要這個輸出:
id DATE nat_locx LOCX distance loc_age
<fct> <date> <dbl> <dbl> <dbl> <dbl>
6553 2004-06-27 2 2 487.90 26
6553 2004-07-14 2 13.5 0 43
6553 2004-07-15 2 12.5 30 44
6553 2004-07-25 2 14.5 44.598 54
6081 2004-07-05 13 14.2 40.249 44
6081 2004-07-20 13 13.8 61.847 49
dplyr優選解決方案。
uj5u.com熱心網友回復:
我們可以使用經典的非向量化if else陳述句:
df %>%
group_by(id) %>%
mutate(nat_locx=if (loc_age > 25 &
loc_age < 40 &
distance > 30) {
first(LOCX)
} else {
nat_locx
}
)
id DATE nat_locx LOCX distance loc_age
<int> <chr> <dbl> <dbl> <dbl> <int>
1 6553 2004-06-27 2 2 488. 26
2 6553 2004-07-14 2 13.5 0 43
3 6553 2004-07-15 2 12.5 30 44
4 6553 2004-07-25 2 14.5 44.6 54
5 6081 2004-07-05 13 14.2 40.2 44
6 6081 2004-07-20 13 13.8 61.8 49
uj5u.com熱心網友回復:
我們可能需要replace
df %>%
group_by(id) %>%
mutate(nat_locx =
replace(nat_locx,
loc_age>25 & loc_age<40 & distance>30,
first(LOCX)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/453405.html
上一篇:在資料驗證源旁邊分配一個數字
