简体   繁体   English

具有多个条件的for循环

[英]for-loop with multiple conditions

I have a database with about 5000 rows and I would like to change the data in one column in a special way, if several conditions are true.我有一个大约有 5000 行的数据库,如果满足多个条件,我想以一种特殊的方式更改一列中的数据。 If the condition is not true, the value will remain the same.如果条件不成立,该值将保持不变。 This is how the data frame looks like:这是数据框的样子:

> testdata
      A  B  C  D  E  F  G
row1 10 10 50 10 50 70 50
row2 10 10 50 70 50 40 60
row3 30 10 50 70 30 20 50
row4 30 30 50 10 10 50 30
row5 10 10 30 10 30 60 40
...

My plan is to change the data in column G under special conditions like this:我的计划是在特殊情况下更改 G 列中的数据,如下所示:

If A = 10 and B = 10 and C = 50 and D = 10 and E = 50 and F = 70, then calculate G - 10如果 A = 10 且 B = 10 且 C = 50 且 D = 10 且 E = 50 且 F = 70,则计算 G - 10

If A = 10 and B = 10 and C = 50 and D = 70 and E = 50 and F = 40, then calculate G - 20如果 A = 10 且 B = 10 且 C = 50 且 D = 70 且 E = 50 且 F = 40,则计算 G - 20

If A = 30 and B = 30 and C = 50 and D = 10 and E = 10 and F = 50, then leave G as it is.如果 A = 30 且 B = 30 且 C = 50 且 D = 10 且 E = 10 且 F = 50,则让 G 保持原样。 ... and so on ... 等等

I have tried to write a for-loop code, but so far it doesn't work and the other discussions on the inte.net about this topic couldn't help me.我曾尝试编写一个 for 循环代码,但到目前为止它不起作用,并且 inte.net 上关于此主题的其他讨论对我没有帮助。 I'm absolutely not sure how to write the right code because I'm a RStudio beginner.我完全不确定如何编写正确的代码,因为我是 RStudio 初学者。

Hope you can help me!希望你能帮我!

testdata <- 
  tibble::tribble(
    ~A,  ~B,  ~C,  ~D,  ~E,  ~F,  ~G,
     10, 10, 50, 10, 50, 70, 50,
     10, 10, 50, 70, 50, 40, 60,
     30, 10, 50, 70, 30, 20, 50,
     30, 30, 50, 10, 10, 50, 30,
     10, 10, 30, 10, 30, 60, 40
  )


library(dplyr)
mutate(testdata, outcome = 
         case_when(
           A == 10 & B == 10 & C == 50 & D == 10 & E == 50 & F == 70 ~  G - 10,
           A == 10 & B == 10 & C == 50 & D == 70 & E == 50 & F == 40 ~  G - 20,
           A == 30 & B == 10 & C == 50 & D == 10 & E == 50 & F == 50 ~  G
         ))

You just have to keep on with your conditions after the last condition.你只需要在最后一个条件之后继续你的条件。

# A tibble: 5 × 8
      A     B     C     D     E     F     G outcome
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>   <dbl>
1    10    10    50    10    50    70    50      40
2    10    10    50    70    50    40    60      40
3    30    10    50    70    30    20    50      NA
4    30    30    50    10    10    50    30      NA
5    10    10    30    10    30    60    40      NA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM