Reputation: 3384
data = data.frame("var1" = c("one", "two", "three", "four", NA))
I seek a data.table fifelse solution so get,
data = data.frame("var1" = c("one", "two", "three", "four", NA),
"var2" = c(10,20,30,40,NA)
The rule is: if var1 = "one" var2 = "10"
if var1 = "two" var2 = "20"
if var1 = "three" var2 = "30"
if var1 = "four" var2 = "40"
And then I hope to label '10', '20', '30', '40' as : dog, cat, fox bird
So how to use multiple fifelse statement and label variable in data.table
Upvotes: 1
Views: 885
Reputation: 887531
If we need to create 'var2', we can pass a named vector to match and create the new 'var2'
library(data.table)
setDT(data)[, var2 := setNames(c(10, 20, 30, 40),
c('one', 'two', 'three', 'four'))[as.character(var1)]]
data[, label := setNames(c('dog', 'cat', 'fox', 'bird'), c(10, 20, 30, 40))[as.character(var2)]][]
data
# var1 var2 label
#1: one 10 dog
#2: two 20 cat
#3: three 30 fox
#4: four 40 bird
#5: <NA> NA <NA>
It may be more efficient to do this with a named vector, but fifelse
can be used as well
setDT(data)[, var2 := fifelse(var1 == 'one', 10,
fifelse(var1 == 'two', 20,
fifelse(var1 == 'three', 30,
fifelse(var1 == 'four', 40, NA_real_))))]
and similarly, for 'label'
Or in the devel
version, there is fcase
setDT(data)[, var2 := fcase(var1 == 'one', 10,
var1 == 'two', 20,
var1 == 'three', 30,
var1 == 'four', 40)]
Upvotes: 1