【问题标题】:Creating a variable with a function in R在 R 中使用函数创建变量
【发布时间】:2019-08-25 21:52:42
【问题描述】:

我想回归以下等式: x5 = B0 + B1(x1-x2) + B2 * max[0,(x2 - x1)] + e

我在生成 max[0,(x0 - x1)] 变量时遇到了一些麻烦。 如果 (x2-x1) =0,则变量应为 (x2-x1) 之间的差。

 d1 <- structure(list(Date=c("2012-01-01", "2012-06-01",
                 "2013-01-01", "2013-06-01", "2014-01-01", "2014-06-01"),
                 x1=c(10, 12, 17L, 29L, 27L, 10L), 
                 x2=c(30L, 19L, 22L, 20L, 11L,24L), 
                 x3=c(28, 23L, 22L, 27L, 21L, 26L),
                 x4=c(30L, 28L, 23L,24L, 10L, 17L), 
                 x5=c(14, 17, 19, 16L, 30L, 26L)),
                 row.names=c(NA, 6L), class="data.frame")
 rownames(d1) <- d1[, "Date"]   
 d1 <- d1[,-1]     

谢谢

【问题讨论】:

    标签: r function variables


    【解决方案1】:

    我们可以使用pmax

    pmax(0, d1$x2 - d1$x1)
    #[1] 20  7  5  0  0 14
    

    这将返回 x2 - x1 或 0 之间的最大值。

    ifelse 方法是

    ifelse(d1$x2 - d1$x1 < 0, 0, d1$x2 - d1$x1)
    #[1] 20  7  5  0  0 14
    

    【讨论】:

    • 第三个好玩的选项:with(d1, (x2 - x1) * ((x2 - x1) &gt; 0))
    猜你喜欢
    • 2015-05-17
    • 1970-01-01
    • 2015-12-14
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 2022-01-15
    相关资源
    最近更新 更多