r - Replacing data.table observations; vector approach -


i replace select values in data.table variable new set of values.

### vector of old values replace char <- c('one', 'two', 'three', 'four', 'five', 'six', 'seven') ### vector of new values replace old values num  <- as.character(1:7)  ### create data.table dt <- data.table(a = c(rep(char, each = 2), c('something', 'else', ' ', '')),                  b = 1:18,                  c = letters[1:18])  ### note warning, appears work expected dt[a == char, := num] 

i following error:

warning messages: 1: in == char :   longer object length not multiple of shorter object length 2: in `[.data.table` (dt, == char, `:=` (a, num)) :   supplied 7 items assigned 2 items of column 'a' (5 unused) 

i curious, what's correct way this?

help appreciated. realize can achieve same result brute force:

data[var == 'seven', var := '7'] data[var == 'six',   var := '6'] ... 

but, introduces redundancy code, , redundancy can lead errors...

use data.table joins:

replacement = data.table(a = char, new_a = num, key = "a")  dt.fixed = replacement[dt][, := ifelse(is.na(new_a), a, new_a)][, new_a := null] 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -