【问题标题】:Writing a function that changes the value in one column based on search in second column in data.table in R编写一个函数,该函数根据 R 中 data.table 中第二列中的搜索更改一列中的值
【发布时间】:2016-09-24 22:14:50
【问题描述】:

所以我编写了一个函数来根据另一列中的值更改一列中的值,因为我需要经常这样做。但是,我无法让它工作。非常感谢您的帮助!

dt <- data.table(mtcars)

ittt <- function(dt, col.a, col.b, if.a, then.b){
  a<-dt[col.a == if.a, col.b := then.b]

  }

a<-ittt(dt = dt, col.a = 'mpg', col.b = 'disp', if.a = 21, then.b = 000)
a

dt[mpg == 21, disp := 999]
dt

【问题讨论】:

  • 看起来ittt &lt;- function(dt, col.a, col.b, if.a, then.b){ expr &lt;- substitute(x == if.a, list(x = as.name(col.a))); dt[eval(expr), (col.b) := then.b][] } 可能会这样做。
  • @RichScriven 谢谢你工作得很好。你介意解释一下expr 部分和最后的[] 吗?
  • 如果您投反对票,请留言说明您为什么不喜欢这个问题。我之前研究过,找不到任何对我有意义的东西(即使现在我也不明白答案),所以我觉得提问是合法的。我还提供了一个可重现的示例。
  • 我投了反对票,因为我认为这不是一个有用的问题(这是反对票的一个很常见的原因)。在我看来(是的,我可以根据我的意见投票),如果你经常做这种事情,你应该通过将更改放入适当的结构(如 data.table)来正式化它,然后合并中的值。为这个简单而常见的任务进行元编程看起来适得其反。
  • 其实我认为这个功能并没有为你节省任何打字。它只会使非常简单的操作难以理解。并且将变量传递给 data.table 语法并不是最自然的事情。

标签: r function data.table


【解决方案1】:

一种方法是。请记住验证函数中的输入,以确保用户传递现有的列名和预期的数据类型。

library(data.table)
dt <- data.table(mtcars)

ittt <- function(dt, col.a, col.b, if.a, then.b, in.place=FALSE){
    ii = substitute(lhs == rhs, list(lhs=as.name(col.a), rhs=if.a))
    jj = substitute(lhs := rhs, list(lhs=as.name(col.b), rhs=then.b))
    if (!in.place) dt = copy(dt)
    dt[eval(ii), eval(jj)][]
}

a<-ittt(dt = dt, col.a = 'mpg', col.b = 'disp', if.a = 21, then.b = 000)
a

# if you update in.place, then no assignment to new variable required
ittt(dt = dt, col.a = 'mpg', col.b = 'disp', if.a = 21, then.b = 000, in.place=TRUE)

我发现这和 Rich 在 cmets 中提出的解决方案几乎相同。

【讨论】:

    【解决方案2】:

    您可以使用[[ 通过将列名称用作变量来获取列。您可以使用 ifelse 对内容应用元素明智的条件。

    ittt <- function(dt, col.a, col.b, if.a, then.b){
        dt[[col.b]] <- ifelse(dt[[col.a]] == if.a, then.b, dt[[col.b]])
        dt
    }
    

    【讨论】:

    • 对不起,这些对我不起作用。它要么仍然找不到 col.b 要么没有改变任何东西
    • 我已经重写了我的答案并进行了测试。这行得通!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2021-11-22
    • 2022-11-01
    • 1970-01-01
    相关资源
    最近更新 更多