本文介绍了如何基于条件语句和dplyr创建新列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

x y
2 4
5 8
1 4
9 12

我有四个条件

  • maxx = 3,minx = 1,maxy = 6,miny = 3(如果minx< x< x< x< y< y< maxy,则z =苹果)
  • maxx = 6,minx = 4,maxy = 9,miny = 7(如果minx< x< x< y< y< y< maxy,则z =球)
  • maxx = 2,minx = 0,maxy = 5,miny = 3(如果minx< x< x< x< y< y< maxy,则z =松树)
  • maxx = 12,minx = 7,maxy = 15,miny = 11(如果minx< x< x< y< y< y< maxy,则z =橙色)

预期结果:

x y z
2 4 apple
5 8 ball
1 4 pine
9 12 orange

我有成千上万的行,并且这四个条件将适合所有值.

I have thousands of rows, and these four conditions that will fit all values.

如何使用mutate函数执行此操作?我知道如何直接操作数字,但不确定如何根据条件语句存储字符.

How can I do this using the mutate function? I know how to manipulate numbers directly, but not sure how I can store a character based on conditional statements.

推荐答案

替代答案:

library(mosaic)
df <- mutate(df, fruit = derivedFactor(
  "apple" = (x<3 & x>1 & y<6 & y>3),
  "ball" = (x<6 & x>4 & y<9 & y>7),
  "pine" = (x<2 & x>0 & y<5 & y>3),
  "orange" = (x<12 & x>7 & y<15 & y>11),
   method ="first",
  .default = NA
))

这篇关于如何基于条件语句和dplyr创建新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 23:20