if/else多个条件R

enyaitl3  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(102)

这里是一个虚拟df

df <- data.frame(
  feature = c("length","weight","roundness","length","weight","roundness"), 
  value = c(7.9,14.2,9.4,30.8,33.7,26.6), 
  gender=c("male","male","male","female","female","female"))

我想在df中添加一个额外的ref列,根据性别组内的一些条件表示一个参考值:
如果圆度值大于15,则按性别分组,否则如果圆度小于15,则打印长度值。下面是我正在寻找的输出。

feature value gender  ref
1    length   7.9   male  7.9
2    weight  14.2   male  7.9
3 roundness   9.4   male  7.9
4    length  30.8 female 26.6
5    weight  33.7 female 26.6
6 roundness  26.6 female 26.6

我想使用if else函数,但我不知道这种情况下的语法,我知道代码是错误的。

df$ref<- df %>% group_by(gender) %>% 
  if (feature%in%"roundness" & df$value > 15 ){value of df roundness} else {(value of df length)}

任何帮助都很感激谢谢

kqqjbcuj

kqqjbcuj1#

一种方法可以是使用tidyr来旋转,并使用dplyr来满足以下条件:

df %>%
  pivot_wider(values_from = value, names_from = feature) %>%
  group_by(gender) %>%
  mutate(ref = case_when(
    roundness > 15 ~ roundness,
    roundness < 15 ~ length
  )) %>%
  pivot_longer(length:roundness)

请注意,如果圆度正好等于15,则不清楚您想要什么,因此您可能希望放置<=>=,而不是仅放置<>-当前代码将为roundness == 15提供NA
输出:

gender   ref name      value
  <chr>  <dbl> <chr>     <dbl>
1 male     7.9 length      7.9
2 male     7.9 weight     14.2
3 male     7.9 roundness   9.4
4 female  26.6 length     30.8
5 female  26.6 weight     33.7
6 female  26.6 roundness  26.6

相关问题