我只想在負數中找到最接近零的數字。當所有列accident1:accident3 都為正時,回傳NA。當所有數字都是負數時,回傳accident1:accident3中負數的最大值。當正數和負數都存在時,只回傳零以下的最大數(包括零)。
資料:
df <- data.frame(id=1:4, accident1=c(-1,-1,3, NA), accident2=c(-5,100, 2, NA), accident3=c(-4,-3,1,NA))
> df
id accident1 accident2 accident3
1 1 -1 -5 -4
2 2 -1 100 -3
3 3 3 2 1
4 4 NA NA NA
試圖:
df %>%
rowwise() %>%
mutate(magic=
case_when(
accident1 < 0 & accident2 < 0 & accident3 < 0 ~ as.numeric(pmax(accident1, accident2, accident3, na.rm=T)),
accident1 > 0 & accident2 > 0 & accident3 > 0 ~ NA_real_,
(accident1 >0 |accident2<0 |accident3<0) & (accident1 >0 |accident2>0 | accident3>0) ~
# need max for cell <0
as.numeric(pmax(accident1, accident2, accident3, na.rm=T)), TRUE~NA_real_))
結果:
id accident1 accident2 accident3 magic
<int> <dbl> <dbl> <dbl> <dbl>
1 1 -1 -5 -4 -1
2 2 -1 100 -3 100
3 3 3 2 1 NA
4 4 NA NA NA NA
期望:
id accident1 accident2 accident3 magic
<int> <dbl> <dbl> <dbl> <dbl>
1 1 -1 -5 -4 -1
2 2 -1 100 -3 -1
3 3 3 2 1 NA
4 4 NA NA NA NA
uj5u.com熱心網友回復:
如果您將資料幀轉換為長格式,您可以更緊湊地執行此操作。(它還可以概括為任意數量的事故型別、 內的缺失事故型別id等......)
sfun <- function(x) {
x <- na.omit(x)
## if x has no non-NA values, all(x>0) will be TRUE
if (all(x>0)) NA_real_ else max(x[x<=0])
}
(df
## convert to long format
%>% pivot_longer(-id)
%>% group_by(id)
## apply summary function to values within id
%>% summarise(magic=sfun(value))
## add original columns back in
%>% full_join(df, by = "id")
)
唯一的區別是該magic列在其余資料之前,而不是在它之后(relocate()如果您愿意,可以添加一個呼叫)
uj5u.com熱心網友回復:
使用sfun@Ben Bolker 的答案中的函式,您也可以這樣做,以寬格式保存資料。使用rowwise和c_across。
library(dplyr)
sfun <- function(x) {
x <- na.omit(x)
if (all(x>0)) NA_real_ else max(x[x<=0])
}
df %>%
rowwise() %>%
mutate(magic = sfun(c_across(starts_with('accident')))) %>%
ungroup
# id accident1 accident2 accident3 magic
# <int> <dbl> <dbl> <dbl> <dbl>
#1 1 -1 -5 -4 -1
#2 2 -1 100 -3 -1
#3 3 3 2 1 NA
#4 4 NA NA NA NA
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352462.html
