我試圖用nat_locx第一行中LOCX的值替換所有distance值,如果我的第一個條件滿足一次或多次id(我的group_by()變數),則用 0 替換所有值,但如果我的第二個條件滿足一次或多次,則不是次id。
這是我的資料示例:
id DATE nat_locx LOCX distance loc_age condition
<fct> <date> <dbl> <dbl> <dbl> <dbl> <lgl>
6553 2004-06-27 13.5 2 487.90 26 TRUE
6553 2004-07-14 13.5 13.5 0 43 FALSE
6553 2004-07-15 13.5 12.5 30 44 FALSE
10160 2005-07-01 4.5 12 229.45588 36 TRUE
10160 2005-07-05 4.5 11 200.12496 40 TRUE
10160 2005-07-06 4.5 11 200.12496 41 TRUE
我嘗試這樣做的方式是這樣的:
df<-df %>%
group_by(id) %>%
mutate(condition = case_when(
loc_age >= 25 & loc_age < 40 & distance > 30 ~ TRUE,
loc_age>=40 & loc_age<50 & distance>60 ~ TRUE,
TRUE ~ FALSE)) %>%
mutate(nat_locx=if(condition=="TRUE") {
first(LOCX) & distance==0.00
} else {
nat_locx})
第一個mutate()結果是一個帶有TRUE和FALSE值的新列。如果甚至有一個實體FALSE,那么if else我之后寫的陳述句不應該繼續進行。
在這個例子中,這意味著 forid==6553回圈不應該改變任何東西。但是,因為condition==TRUE對于每一行,id==10160都if else應該繼續。
理想情況下,我想要這個輸出:
id DATE nat_locx LOCX distance loc_age condition
<fct> <date> <dbl> <dbl> <dbl> <dbl> <lgl>
6553 2004-06-27 13.5 2 487.90 26 TRUE
6553 2004-07-14 13.5 13.5 0 43 FALSE
6553 2004-07-15 13.5 12.5 30 44 FALSE
10160 2005-07-01 12 12 0 36 TRUE
10160 2005-07-05 12 11 0 40 TRUE
10160 2005-07-06 12 11 0 41 TRUE
dplyr優選解決方案。
uj5u.com熱心網友回復:
正如@Ben 提到的,我們可以包含all,以便更改僅應用于具有 all 的組TRUE。我們可以將其用于列nat_locx和distance列。
library(tidyverse)
df %>%
group_by(id) %>%
mutate(
condition = case_when(
loc_age >= 25 & loc_age < 40 & distance > 30 ~ TRUE,
loc_age >= 40 & loc_age < 50 & distance > 60 ~ TRUE,
TRUE ~ FALSE
)
) %>%
mutate(nat_locx = if (all(condition)) first(LOCX) else nat_locx,
distance = if (all(condition)) 0 else distance)
輸出
id DATE nat_locx LOCX distance loc_age condition
<int> <chr> <dbl> <dbl> <dbl> <int> <lgl>
1 6553 2004-06-27 13.5 2 488. 26 TRUE
2 6553 2004-07-14 13.5 13.5 0 43 FALSE
3 6553 2004-07-15 13.5 12.5 30 44 FALSE
4 10160 2005-07-01 12 12 0 36 TRUE
5 10160 2005-07-05 12 11 0 40 TRUE
6 10160 2005-07-06 12 11 0 41 TRUE
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/454436.html
