Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing data.table observations; vector approach

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...

like image 272
Andreas Avatar asked Aug 07 '26 23:08

Andreas


1 Answers

Use data.table joins:

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]
like image 192
eddi Avatar answered Aug 10 '26 18:08

eddi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!