【问题标题】:R: Smart way to replace column/vector values by multiple rules?R:用多个规则替换列/向量值的聪明方法?
【发布时间】:2020-12-08 09:09:53
【问题描述】:

在几个阈值和计算之后,我需要将原始值重新编码为 0-1。这是公式的样子:

我认为这只是说:

  • 如果 x x = 0
  • 如果 x > 60 & x = 0.05*x -3
  • 如果 x > 80 -> x = 1

这是我的方法:

# V is from 0-600 m3/ha
set.seed(3)
V_pine = sample.int(100, 10)  # generate 10 random numbers up to 100

> V_pine
[1]  5 58 12 36 99 95  8 20 74 55

# Recode values following multiple ifelse statements
for (i in V_pine){
  if (i <= 60) {
    i <- 0
    } else if (i > 60 & i<= 80) {
      i <- (0.05* i )-3
    } else if (i > 80) {
      i<- 1
    }
  print(i)
}

似乎这会带来正确的结果:

Output: 
0 0 0 0 1 1 0 0 0.7 0

然而,由于我还有许多类似的函数/公式,我想知道是否有另一种方法可以简化for loopifelse 语句?

我的数据将存储在data.frame 中,因此使用dplyrmutate 会很棒。感谢您的建议!

【问题讨论】:

    标签: r function dplyr


    【解决方案1】:

    您可以从dplyr 使用case_when

    library(tidyverse)
    
    #Using your data as data.frame
    set.seed(3)
    df <- data.frame(V_pine = sample.int(100, 10))
    
    df %>% 
      mutate(
        recode = case_when(
          V_pine < 60 ~ 0, 
          V_pine > 60 & V_pine <= 80  ~ 0.05*V_pine-3, 
          V_pine > 80  ~ 1, 
        ))
    

    输出:

         V_pine recode
    1      17      0
    2      80      1
    3      38      0
    4      32      0
    5      58      0
    6      96      1
    7      12      0
    8      28      0
    9      54      0
    10     95      1
    

    【讨论】:

    • 您的解决方案看起来不错。我不认为你使用了正确的种子。
    • 我使用了相同的种子,我想我不知道为什么它给了我不同的数字。可能是因为他用samle.int创建了一个向量,我用了一个数据框?
    • 我在运行您的代码时获得了 OP 的 V_pine 值。也许再运行一次看看。
    【解决方案2】:

    使用基础 R

    df$recode <- ifelse(df$V_pine <= 60, 0, ifelse(df$V_pine > 80, 1, df$V_pine*0.05 - 3))
    df
    
       V_pine recode
    1       5    0.0
    2      58    0.0
    3      12    0.0
    4      36    0.0
    5      99    1.0
    6      95    1.0
    7       8    0.0
    8      20    0.0
    9      74    0.7
    10     55    0.0
    

    【讨论】:

      猜你喜欢
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 2021-08-05
      相关资源
      最近更新 更多