[英]Row-wise min() on right hand when using dplyr::case_when
I am trying to fetch the smaller of one variable at one observation and a fixed number in a conditional dplyr::case_when statement in R. But the min() statement compares to the smallest observation of the entire variable vector, ie not for each observation. 我试图在一次观察中获取一个变量中较小的变量,并在R中的条件dplyr :: case_when语句中获取一个固定数。但是min()语句与整个变量向量的最小观察值进行比较,即不是针对每个观察值。
library(tidyverse)
data_frame(spc = rep(c("cat", "dog"), 3), z = 1:6) %>%
mutate(
dogsmax3 = case_when(
spc == "dog" ~ min(z, 3),
TRUE ~ 0))
# spc z dogsmax3
# <chr> <int> <dbl>
#1 cat 1 0
#2 dog 2 1
#3 cat 3 0
#4 dog 4 1
#5 cat 5 0
#6 dog 6 1
While I look for a statement making this result: 当我寻找产生此结果的语句时:
# spc z dogsmax3
# <chr> <int> <dbl>
#1 cat 1 0
#2 dog 2 2
#3 cat 3 0
#4 dog 4 3
#5 cat 5 0
#6 dog 6 3
So, any suggestions for a better apprach? 那么,对于更好的方法有什么建议吗?
Use rowwise
. 使用
rowwise
。 Instead of case_when
you could also use an ifelse
: 取而代之的
case_when
你也可以使用一个ifelse
:
library(tidyverse)
data_frame(spc = rep(c("cat", "dog"), 3), z = 1:6) %>%
rowwise() %>%
mutate(dogsmax3 = ifelse(spc == "dog", min(z,3), 0)) %>%
ungroup() ## to revert the grouping by rows
You can use ?pmin
instead of min
- 您可以使用
?pmin
代替min
data_frame(spc = rep(c("cat", "dog"), 3), z = 1:6) %>%
mutate(
dogsmax3 = case_when(
spc == "dog" ~ pmin(z, 3),
TRUE ~ 0)
)
# A tibble: 6 x 3
spc z dogsmax3
<chr> <int> <dbl>
1 cat 1 0
2 dog 2 2.00
3 cat 3 0
4 dog 4 3.00
5 cat 5 0
6 dog 6 3.00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.