我在 dplyr 管道内的
which.min
函数上遇到一些问题
我有一个麻烦的solution (*)
,我正在寻找更紧凑和优雅的方式来做到这一点
library(dplyr)
data=data.frame(s1=c(10,NA,5,NA,NA),s2=c(8,NA,NA,4,20),s3=c(NA,NA,2,NA,10))
data
#> s1 s2 s3
#> 1 10 8 NA
#> 2 NA NA NA
#> 3 5 NA 2
#> 4 NA 4 NA
#> 5 NA 20 10
这里用
min(x,na.rm=TRUE)
我可以提取最小值
data%>%
rowwise()%>%
mutate(Min_s=min(c(s1,s2,s3),na.rm=TRUE))
#> Warning: There was 1 warning in `mutate()`.
#> ℹ In argument: `Min_s = min(c(s1, s2, s3), na.rm = TRUE)`.
#> ℹ In row 2.
#> Caused by warning in `min()`:
#> ! no non-missing arguments to min; returning Inf
#> # A tibble: 5 × 4
#> # Rowwise:
#> s1 s2 s3 Min_s
#> <dbl> <dbl> <dbl> <dbl>
#> 1 10 8 NA 8
#> 2 NA NA NA Inf
#> 3 5 NA 2 2
#> 4 NA 4 NA 4
#> 5 NA 20 10 10
这里我无法提取哪个变量包含最小值
data%>%
rowwise()%>%
mutate(which_s=which.min(c(s1,s2,s3)))
#> Error in `mutate()`:
#> ℹ In argument: `which_s = which.min(c(s1, s2, s3))`.
#> ℹ In row 2.
#> Caused by error:
#> ! `which_s` must be size 1, not 0.
#> ℹ Did you mean: `which_s = list(which.min(c(s1, s2, s3)))` ?
# Solution (*)
data%>%
rowwise()%>%
mutate(which_s=if(!is.na(s1)|!is.na(s2)|!is.na(s3)) {which.min(c(s1,s2,s3))} else NA )
#> # A tibble: 5 × 4
#> # Rowwise:
#> s1 s2 s3 which_s
#> <dbl> <dbl> <dbl> <int>
#> 1 10 8 NA 2
#> 2 NA NA NA NA
#> 3 5 NA 2 3
#> 4 NA 4 NA 2
#> 5 NA 20 10 3
创建于 2024-11-07,使用 reprex v2.1.0
在第二行中,您将在
integer(0)
列中获得which_s
,这就是您无法在没有错误的情况下运行它的点。
相反,您可以首先将结果存储在列表中,然后
unnest
(不要忘记在keep_empty
中启用unnest
参数)
data %>%
rowwise() %>%
mutate(which_s = list(which.min(c(s1, s2, s3)))) %>%
unnest(which_s, keep_empty = TRUE)
这给出了
# A tibble: 5 × 4
s1 s2 s3 which_s
<dbl> <dbl> <dbl> <int>
1 10 8 NA 2
2 NA NA NA NA
3 5 NA 2 3
4 NA 4 NA 2
5 NA 20 10 3