【问题标题】:R: Looping a custom function over specific rows and columnsR:在特定的行和列上循环自定义函数
【发布时间】:2019-01-21 09:57:57
【问题描述】:

我想遍历选择的列及其所有行,并应用 If Else 嵌套函数以替换所有元素。

Table[c("Pb","Pc","Pd","Pe","Pf")] <-  lapply(Table[c("Pb","Pc","Pd","Pe","Pf")], function(x) {
                                       if (x <0.50) {round_any(x,0.05)}
                                  else if (x <1.00) {round_any(x,0.10)}
                                  else if (x <2.00) {round_any(x,0.25)}
                                  else if (x <5.00) {round_any(x,0.50)}
                                  else              {round_any(x,1)}
                                              })

代码运行,但我收到以下警告: 1: In if (x &lt; 0.5) { ... : the condition has length &gt; 1 and only the first element will be used结果并不完全符合我的预期。有没有其他方法可以产生这个输出?

【问题讨论】:

  • 列的长度大于 1,if/else 仅适用于长度 1。您可能需要 ifelse
  • 谢谢@akrun。我根据你的提示解决了它:)

标签: r apply lapply


【解决方案1】:
Table[c("Pb","Pc","Pd","Pe","Pf")] <- lapply(Table[c("Pb","Pc","Pd","Pe","Pf")], function(x) {
                                       ifelse (x <0.50, round_any(x,0.05),
                                       ifelse (x <1.00, round_any(x,0.10),
                                       ifelse (x <2.00, round_any(x,0.25),
                                       ifelse (x <5.00, round_any(x,0.50), 
                                               round_any(x,1)))))})

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2023-03-16
    相关资源
    最近更新 更多