取代数据。观察;矢量方法

时间:2013-05-09 19:56:06

标签: r functional-programming data.table

我想用一组新的值替换data.table变量中的选择值。

### Vector of old values I would like to replace
char <- c('one', 'two', 'three', 'four', 'five', 'six', 'seven')
### Vector of new values I would like to replace old values with
num  <- as.character(1:7)

### Create a data.table
dt <- data.table(a = c(rep(char, each = 2), c('Something', 'Else', ' ', '')),
                 b = 1:18,
                 c = letters[1:18])

### Note the warning, but also that it appears to work as expected
dt[a == char, a := num]

我收到以下错误:

Warning messages:
1: In a == char :
  longer object length is not a multiple of shorter object length
2: In `[.data.table` (dt, a == char, `:=` (a, num)) :
  Supplied 7 items to be assigned to 2 items of column 'a' (5 unused)

我很好奇,这样做的正确方法是什么?

帮助表示赞赏。我确实意识到我可以用蛮力取得同样的结果:

data[var == 'Seven', var := '7']
data[var == 'Six',   var := '6']
...

但是,这会在代码中引入冗余,冗余会导致错误......

1 个答案:

答案 0 :(得分:5)

使用data.table加入:

replacement = data.table(a = char, new_a = num, key = "a")

dt.fixed = replacement[dt][, a := ifelse(is.na(new_a), a, new_a)][, new_a := NULL]