编写一个函数,根据R中data.table中第二列中的搜索,更改一列中的值

时间:2016-09-24 22:14:50

标签: r function data.table

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

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

2 个答案:

答案 0 :(得分: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在评论中提出的解决方案几乎相同。

答案 1 :(得分:0)

您可以使用[[使用其名称作为变量来获取列。您可以使用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
}