3

I would like to replace select values in a data.table variable with a new set of values.

### 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]

I get the following error:

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)

I am curious, what's the correct way to do this?

Help is appreciated. I do realize that I can achieve the same result with brute force:

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

But, this introduces redundancy into the code, and redundancy can lead to errors...

4

1 回答 1

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]
于 2013-05-09T20:04:58.297 回答